﻿/********************************************************
 * Module Name    : Search/HighVolume
 * Purpose        : To search records through lookup
 * Class Used     : MUserQuery.cs, MUserQueryLine.cs
 * Chronological Development
 * Raghunandan sharma     8-Nov-2010
  ******************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Text;
using System.Windows.Forms;
using VAdvantage.Common;
using VAdvantage.DataBase;
using VAdvantage.Classes;
using System.Collections;
using VAdvantage.SqlExec;
using VAdvantage.Model;
using VAdvantage.Process; using VAdvantage.ProcessEngine;
using VAdvantage.Controls;
using VAdvantage.Utility;
using VAdvantage.Logging;
using VAdvantage.Grids;
using System.Data;
using System.Collections.ObjectModel;
using System.Windows.Markup;

using System.ComponentModel;
using System.Threading;
using System.Reflection;

namespace VAdvantage.Framework
{
    /// <summary>
    /// Form to search records
    /// </summary>
    public partial class Find : ChildWindow
    {
        #region "Variables"


        enum TabIndex
        {
            enmDefault = 0,
            enmAdvanced = 1,
            enmFrame = 2,
            enmFrameAccess = 3,
            enmKPI = 4,
            enmKPIAccess = 5
        }

        //timer for listbox
        bool singleClick = false;
        System.Windows.Threading.DispatcherTimer timer;

        // Target Window No
        private int _targetWindowNo;
        // Context
        private Context _ctx = Utility.Envs.GetContext();
        // The Tab
        private int _AD_Tab_ID;
        //	Table ID
        private int _AD_Table_ID;
        // Table Name
        private string _tableName;
        // Where
        private string _whereExtended;
        // Search Fields
        private GridField[] _findFields;
        // Button Fields
        //private ArrayList<Integer> _buttonFields = new ArrayList<Integer>();
        // Resulting query
        private Query _query = null;
        //	History Days (0=all)
        private int _days = 0;
        //	History Created Flag
        private bool _created = true;
        // Number of records
        private int _total;
        private bool _hasName = false;
        private bool _hasDescription = false;
        private bool _hasSearchKey = false;
        private bool _hasDocNo = false;
        //	Line in Simple Content
        private int _lineNo = 3;
        //
        private bool _isSaveError = false;
        // Length of Fields on first tab
        private const int FIELDLENGTH = 20;
        //	For Grid Controller
        private const int TABNO = 99;
        //private SortedList<string, string> srtList = null;//silverlight doesn't support sortedlist
        private Dictionary<string, string> srtList = null;

        //	List of IControl
        private List<IControl> _sEditors = new List<IControl>();

        private DataSet dsAdvanceData = null;

        private DataSet dsAccess = null;

        private string _gridColHead;
        private string _gridOptrHead;
        private string _gridValue1Head;
        private string _gridValue2Head;

        private bool _isLoadError;
        private bool _isOkPressed = false;
        private bool _isOkButtonPressed = false;

        GridTab curTab = null;



        private bool hasValue = false;
        private bool hasDocNo = false;
        private bool hasName = false;
        private bool hasDescription = false;

        private Dictionary<int, GridField> m_targetFields = new Dictionary<int, GridField>();




        #endregion

        int _minRecord = 0;
        private Logging.VLogger log = Logging.VLogger.GetVLogger(typeof(Find).FullName);
        SilverlightDesktop.Common.DoubleClickHelper helper;

        public Find()
        { }

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="targetWindowNo">window number</param>
        /// <param name="title">title to be shown on window</param>
        /// <param name="AD_Tab_ID">AD_Tab_ID</param>
        /// <param name="AD_Table_ID">AD_Table_ID</param>
        /// <param name="tableName">table name</param>
        /// <param name="whereExtended">where query</param>
        /// <param name="findFields">array of fieldobj</param>
        /// <param name="minRecords">minimum records</param>
        public Find(int targetWindowNo, string title, int AD_Tab_ID, int AD_Table_ID, string tableName,
            string whereExtended, GridField[] findFields, int minRecords, bool openFrame)
        //: base(true, false, false, false, Msg.GetMsg(Env.GetContext(), "Find", true) + " : " + title)
        {

            base.Title = Msg.GetMsg(Envs.GetContext(), "Find", true);
            // store values
            _minRecord = minRecords;
            _targetWindowNo = targetWindowNo;
            _AD_Tab_ID = AD_Tab_ID;
            _AD_Table_ID = AD_Table_ID;
            _tableName = tableName;
            _whereExtended = whereExtended;
            _findFields = findFields;
            //
            _query = new Query(tableName);
            _query.AddRestriction(whereExtended);

            //this.BackColor = DataBase.GlobalVariable.WINDOW_BACK_COLOR;

            try
            {
                InitializeComponent();
                vtxtName.Visible = false;
                vtxtDesc.Visible = false;
                vtxtDocNo.Visible = false;
                vtxtSearchKey.Visible = false;

                vlblName.Visible = false;
                vlblDesc.Visible = false;
                vlblDocNo.Visible = false;
                vlblSearchKey.Visible = false;
                LayoutRoot.Background = new SolidColorBrush(DataBase.GlobalVariable.WINDOW_BACK_COLOR);
                // set font
                //InitialFormSetting.SetFont(this);//comment for silverlight

                InitFind();
                
                cmbBGColor.SelectedValuePath = "Key";
                cmbBGColor.DisplayMemberPath = "Name";


                if (openFrame)
                {
                    vtabLookup.SelectedIndex = (int)TabIndex.enmFrame;
                }
                // if total records < minimum records, then close this window
                //if (_total < minRecords)
                //{
                //    _isLoadError = true;
                //    return;
                //}
            }
            catch (Exception ex)
            {
                log.Log(Level.SEVERE, "Find", ex);
            }

            //
            //this.Loaded += new RoutedEventHandler(theList_Loaded);load list on load event
            //timer = new System.Windows.Threading.DispatcherTimer();
            //timer.Interval = TimeSpan.FromMilliseconds(500);
            //timer.Tick += new EventHandler(timer_Tick);
            //ScrollViewer sc=lstQuery.get
        }


        public Find(int targetWindowNo, GridTab _curTab, GridField[] findFields, int minRecords, bool openFrame)
            : this(targetWindowNo, _curTab.GetName(), _curTab.GetAD_Tab_ID(), _curTab.GetAD_Table_ID(), _curTab.GetTableName(), _curTab.GetWhereClause(), findFields, minRecords, openFrame)
        {
            curTab = _curTab;
        }

        void helper_Click(object sender, MouseButtonEventArgs e)
        {

        }

        void helper_DoubleClick(object sender, MouseButtonEventArgs e)
        {
            //try for double click list
            object xx = lstQuery.SelectedItem;
            if (xx != null)
            {
                SetBusy(true);
                string val = ((ValueNamePair)xx).Key.ToString();
                if (lstQuery.SelectedIndex < 9)
                {
                    string[] valSplit = val.Split('|');
                    int cnt = valSplit.Length;
                    if (cnt == 1)
                    {
                        _created = false;
                    }
                    else
                    {
                        _created = true;
                    }

                    _days = int.Parse(valSplit[0]);
                    val = "";
                }
                else
                {
                    _days = 0;
                }

                    _query = new Query(_tableName);
                    _query.AddRestriction(val);

             
                    int no = 0;
                    System.Threading.ThreadPool.QueueUserWorkItem(delegate
                    {
                         no=  GetNoOfRecords(_query, true);
                         _query.SetRecordCount(no);

                         System.Windows.Deployment.Current.Dispatcher.BeginInvoke(delegate
                             {
                                 SetBusy(false);
                                 if (no != 0)
                                 {
                                     _isOkButtonPressed = true;
                                     Close(_isOkButtonPressed);
                                 }
                             });
                    });
            }
            else
            {
                SetBusy(false);
                _isOkButtonPressed = false;
                _isOkPressed = false;
                Close(_isOkButtonPressed);
            }

        }


        private void Close(bool isOkPressed)
        {
            this.DialogResult = isOkPressed;
        }



        #region "Public Functions"

        /// <summary>
        /// Get Query - Retrieve result
        /// </summary>
        /// <returns>String representation of query</returns>
        public Query GetQuery()
        {
            MRole role = MRole.GetDefault();
            if (role.IsQueryMax(GetTotalRecords()))
            {
                _query = Query.GetNoRecordQuery(_tableName, false);
                _total = 0;
                log.Warning("Query - over max");
            }
            else
                log.Info("Query=" + _query);
            return _query;
        }

        /// <summary>
        /// Get selected number of days
        /// </summary>
        /// <returns>days or -1 for all</returns>
        public int GetCurrentDays()
        {
            return _days;
        }

        /// <summary>
        /// Get created or updated
        /// </summary>
        /// <returns>bool type-true if created</returns>
        public bool GetIsCreated()
        {
            return _created;
        }

        /// <summary>
        /// Get OK button pressed
        /// </summary>
        /// <returns>bool type-true if OK Button pressed</returns>
        public bool GetIsOKPressed()
        {
            return (_isOkButtonPressed && _isOkPressed);
        }

        /// <summary>
        /// Get Total Records
        /// </summary>
        /// <returns>no of records</returns>
        public int GetTotalRecords()
        {
            return _total;
        }

        /// <summary>
        /// If Load
        /// </summary>
        /// <returns>bool type-true if loaded successfully</returns>
        public bool IsLoadError()
        {
            return _isLoadError;
        }

        #endregion

        #region "First Tab Functions "
        /// <summary>
        /// Find Fields
        /// </summary>
        private void InitFindold()
        {
            SetBusy(true);
            DataSet dsListQueries = null;
           



            string tName = "", tDesc = "", tValue = "", tDoc = "";

            BackgroundWorker bgw = new BackgroundWorker();

            bgw.DoWork += (sd, ed) =>
                {
                    _total = GetNoOfRecords(null, false);
                    dsListQueries = MUserQuery.GetDataSet(_ctx, _AD_Tab_ID, _AD_Table_ID, "Code");

                    tName = Msg.Translate(_ctx, "Name");
                    tDesc = Msg.Translate(_ctx, "Description");
                    tValue = Msg.Translate(_ctx, "Value");
                    tDoc = Msg.Translate(_ctx, "DocumentNo");
                };

            bgw.RunWorkerCompleted += (sc, ec) =>
                {
                    SetStatusDB(_total);
                    FillList(dsListQueries);
                    SetBusy(false);

                    vlblName.Content = tName;
                    vlblDesc.Content = tDesc;
                    vlblSearchKey.Content = tValue;
                    vlblDocNo.Content = tDoc;

                };
            bgw.RunWorkerAsync();

            CommonFunctions.ShowMessage("", lblStatusBar);
            //	Get field Info from target Tab
            for (int i = 0; i < _findFields.Length; i++)
            {
                GridField field = _findFields[i];
                if (field.IsEncrypted())
                    continue;
                if (!field.IsDisplayed())
                    continue;
                string columnName = field.GetColumnName();

                // check for default fields
                // Name
                if (columnName.Equals("Name"))
                {
                    _hasName = true;
                    vtxtName.Visible = true;
                    vlblName.Visible = true;
                    vlblName.Content = Msg.Translate(_ctx, "Name");
                }
                // Description
                else if (columnName.Equals("Description"))
                {
                    _hasDescription = true;
                    vtxtDesc.Visible = true;
                    vlblDesc.Visible = true;
                    vlblDesc.Content = Msg.Translate(_ctx, "Description");
                }
                // Value
                else if (columnName.Equals("Value"))
                {
                    _hasSearchKey = true;
                    vtxtSearchKey.Visible = true;
                    vlblSearchKey.Visible = true;
                    vlblSearchKey.Content = Msg.Translate(_ctx, "Value");
                }
                // DocumentNo
                else if (columnName.Equals("DocumentNo"))
                {
                    _hasDocNo = true;
                    vtxtDocNo.Visible = true;
                    vlblDocNo.Visible = true;
                    vlblDocNo.Content = Msg.Translate(_ctx, "DocumentNo");
                }
                // fields whose "IsSelectionColumn" is set to true
                else if (field.IsSelectionColumn())
                {
                    // add the control of this field
                    AddSelectionColumn(field);
                }
                else if (columnName.IndexOf("Name") != -1)
                {
                    AddSelectionColumn(field);
                }
            }
            //silverlight comment
            // set height of the form
            //if (tblpnlS.Height > pnlSCtl.Height)
            //{
            //    this.Height = this.Height + tblpnlS.Height - pnlSCtl.Height;
            //}

            //	Get Total

            

            //System.Threading.ThreadPool.QueueUserWorkItem(delegate
            //{
               
            //    System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => );
            //});
            // display total records on status bar
            //SetStatusDB(_total);
        }


        /// <summary>
        /// Dynamic Init = Find Fields InfoProduct
        /// Set up GridController
        /// </summary>
        private void InitFind()
        {
            log.Config("");
            SetBusy(true);
            DataSet dsListQueries = null;

            List<GridField> specificSelectionCols = new List<GridField>();
            List<GridField> unassignedSelectionCols = new List<GridField>();

             string tName = "", tDesc = "", tValue = "", tDoc = "";

            BackgroundWorker bgw = new BackgroundWorker();

            bgw.DoWork += (sd, ed) =>
                {
                    _total = GetNoOfRecords(null, false);
                    dsListQueries = MUserQuery.GetDataSet(_ctx, _AD_Tab_ID, _AD_Table_ID, "Code");

                    tName = Msg.Translate(_ctx, "Name");
                    tDesc = Msg.Translate(_ctx, "Description");
                    tValue = Msg.Translate(_ctx, "Value");
                    tDoc = Msg.Translate(_ctx, "DocumentNo");
                };

            bgw.RunWorkerCompleted += (sc, ec) =>
                {
                    SetStatusDB(_total);
                    FillList(dsListQueries);
                    SetBusy(false);

                    vlblName.Content = tName;
                    vlblDesc.Content = tDesc;
                    vlblSearchKey.Content = tValue;
                    vlblDocNo.Content = tDoc;

                };
            bgw.RunWorkerAsync();

            // Get Info from target Tab
            foreach (GridField mField in _findFields)
            {
                if (mField.IsEncrypted())
                    continue;
                if (!mField.IsDisplayed())
                    continue;
                String columnName = mField.GetColumnName();

                if (columnName.Equals("Value"))
                    hasValue = true;
                else if (columnName.Equals("Name"))
                    hasName = true;
                else if (columnName.Equals("DocumentNo"))
                    hasDocNo = true;
                else if (columnName.Equals("Description"))
                    hasDescription = true;
                else if (mField.IsSelectionColumn() || (columnName.IndexOf("Name") != -1))
                {
                    if (mField.GetSelectionSeqNo() == 0)
                    {
                        unassignedSelectionCols.Add(mField);
                    }
                    else
                    {
                        bool added = false;
                        for (int i = 0; i < specificSelectionCols.Count; i++)
                        {
                            if (mField.GetSelectionSeqNo() <= specificSelectionCols[i].GetSelectionSeqNo())
                            {
                                specificSelectionCols.Insert(i, mField);
                                added = true;
                                break;
                            }
                        }
                        if (!added)
                            specificSelectionCols.Add(mField);
                    }
                }

                //  TargetFields
                m_targetFields.Add(Util.GetValueOfInt(mField.GetAD_Column_ID()), mField);
            }   //  for all target tab fields


            foreach (GridField selectionCol in specificSelectionCols)
            {
                AddSelectionColumn(selectionCol);
            }
            foreach (GridField selectionCol in unassignedSelectionCols)
            {
                AddSelectionColumn(selectionCol);
            }

            //Value
            if (hasValue)
            {
                _hasSearchKey = true;
                vtxtSearchKey.Visible = true;
                vlblSearchKey.Visible = true;
                vlblSearchKey.Content = Msg.Translate(_ctx, "Value");
            }
            //if (hasValue)
            //{
            //    valueField.addActionListener(this);
            //}
            // DocumentNo
            if (hasDocNo)
            {
                _hasDocNo = true;
                vtxtDocNo.Visible = true;
                vlblDocNo.Visible = true;
                vlblDocNo.Content = Msg.Translate(_ctx, "DocumentNo");
            }
            // Name
            if (hasName)
            {
                _hasName = true;
                vtxtName.Visible = true;
                vlblName.Visible = true;
                vlblName.Content = Msg.Translate(_ctx, "Name");
            }
            //Description
            if (hasDescription)
            {
                _hasDescription = true;
                vtxtDesc.Visible = true;
                vlblDesc.Visible = true;
                vlblDesc.Content = Msg.Translate(_ctx, "Description");
            }
            //// set height of the form
            //if (tblpnlS.Height > pnlSCtl.Height)
            //{
            //    this.Height = this.Height + tblpnlS.Height - pnlSCtl.Height;
            //}
            // Get Total
           // _total = GetNoOfRecords(null, false);
            //SetStatusDB(_total);

        }



        /// <summary>
        /// Get the number of records of target tab
        /// </summary>
        /// <param name="query">query where clause for target tab</param>
        /// <param name="alertZeroRecords">show dialog if there are no records</param>
        /// <returns>number of selected records</returns>
        private int GetNoOfRecords(Query query, bool alertZeroRecords)
        {
            // make query
            StringBuilder sql = new StringBuilder("SELECT COUNT(*) FROM ");
            sql.Append(_tableName);
            bool hasWhere = false;
            // add where clause if already exists
            if (_whereExtended != null && _whereExtended.Length > 0)
            {
                if (_whereExtended.IndexOf("@") == -1)
                {
                    sql.Append(" WHERE ").Append(_whereExtended);
                }
                else
                {
                    sql.Append(" WHERE ").Append(Envs.ParseContext(_ctx, _targetWindowNo, _whereExtended, false));
                }
                hasWhere = true;
            }
            // if user has given any query
            if (query != null && query.IsActive())
            {
                // if where clause is started, then add "AND"
                if (hasWhere)
                {
                    sql.Append(" AND ");
                }
                // add "WHERE"
                else
                {
                    sql.Append(" WHERE ");
                }
                sql.Append(query.GetWhereClause());
            }
            //	Add Access
            string finalSQL = MRole.GetDefault().AddAccessSQL(sql.ToString(), _tableName,
                MRole.SQL_NOTQUALIFIED, MRole.SQL_RO);
            //finalSQL = Env.ParseContext(_ctx, _targetWindowNo, finalSQL, false);

            _ctx.SetContext(_targetWindowNo, TABNO, "FindSQL", finalSQL);

            //  Execute Query
            _total = 999999;

            //System.Threading.ThreadPool.QueueUserWorkItem(delegate
            //{
            //    try
            //    {
            //        //_total = int.Parse(ExecuteQuery.ExecuteScalar(finalSQL));
            //        _total = DataBase.DB.GetSQLValue(null, finalSQL, null);
            //    }
            //    catch (Exception ex)
            //    {
            //        log.Log(Level.SEVERE, finalSQL, ex);
            //    }
            //    System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => GetTotal(_total, query, alertZeroRecords));

            //});
            try
            {

                //_total = int.Parse(ExecuteQuery.ExecuteScalar(finalSQL));
                _total = DataBase.DB.GetSQLValue(null, finalSQL, null);
            }
            catch (Exception ex)
            {
                log.Log(Level.SEVERE, finalSQL, ex);
            }
            MRole role = MRole.GetDefault();
            //	No Records
            if (_total == 0)
            {
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => TotalCheck(alertZeroRecords));
            }
            //	More then allowed
            else if (query != null && role.IsQueryMax(_total))
            {
                ShowMessage.Error("FindOverMax", true, _total + " > " + role.GetMaxQueryRecords());//silverlight
                //MessageBox.Show("FindZeroRecords " + _total + " > " + role.GetMaxQueryRecords());
            }
            else
            {
                _isOkPressed = true;
                log.Config("#" + _total);
            }
            // show query's where clause on status bar
            if (query != null)
            {
                //CommonFunctions.ShowMessage(query.GetWhereClause(), lblStatusBar);
            }
            return _total;
        }

        //private int GetTotal(int _total, Query query, bool alertZeroRecords)
        //{
        //    MRole role = MRole.GetDefault();
        //    //	No Records
        //    if (_total == 0)
        //    {
        //        System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => TotalCheck(alertZeroRecords));

        //    }
        //    //	More then allowed
        //    else if (query != null && role.IsQueryMax(_total))
        //    {
        //        //ShowMessage.Error("FindOverMax", true, _total + " > " + role.GetMaxQueryRecords());//silverlight
        //        MessageBox.Show("FindZeroRecords " + _total + " > " + role.GetMaxQueryRecords());
        //    }
        //    else
        //    {
        //        _isOkPressed = true;
        //        log.Config("#" + _total);
        //    }
        //    // show query's where clause on status bar
        //    if (query != null)
        //    {
        //        //CommonFunctions.ShowMessage(query.GetWhereClause(), lblStatusBar);
        //    }
        //    return _total;
        //}

        private void TotalCheck(bool alertZeroRecords)
        {
            if (vtabLookup.SelectedIndex == (int)TabIndex.enmAdvanced && vtxtQueryName.Text.Trim() != "" && !_isSaveError && (vcmbQueryA.SelectedValue == null || vcmbQueryA.SelectedValue.ToString() == "0"))
            {
                // if no record found and user has saved any query in database
                // then fill the query combo again
                FillQuery();
                // select the newly inserted query
                
            }
            if (alertZeroRecords)
            {
                _isOkPressed = false;
                _isOkButtonPressed = false;
                ShowMessage.Info("FindZeroRecords", true, "", null);//silverlight
                //MessageBox.Show("FindZeroRecords");
            }
        }

        /// <summary>
        /// Display current count
        /// </summary>
        /// <param name="currentCount">total count</param>
        private void SetStatusDB(int currentCount)
        {
            string text = " " + currentCount + " / " + _total + " ";
            // show records on status bar
            //CommonFunctions.ShowMessage(text, lblStatusRecord);//silverlight comment
            CommonFunctions.ShowMessage(text, lblStatusBar);

            if (_total < _minRecord)
            {
                _isLoadError = true;
                return;
            }
        }

        /// <summary>
        /// Add Selection Column to first Tab (Simple)
        /// </summary>
        /// <param name="field">field</param>
        private void AddSelectionColumn(GridField field)
        {
            // set display length for the control
            int displayLength = field.GetDisplayLength();
            if (displayLength > FIELDLENGTH)
                field.SetDisplayLength(FIELDLENGTH);
            else
                displayLength = 0;

            //	get control according to the field
            IControl ctrl = null;
            if (field.IsLookup())
            {
                if (field.GetLookup() != null && (field.GetLookup().GetValidation().IndexOf("@") != -1 || field.GetLookup().GetDisplayType() == DisplayType.Search))
                {
                    int displayType = field.GetDisplayType();
                    field.SetDisplayType(DisplayType.Search);
                    ctrl = VControlFactory.GetControl(null, field, true, false, false);
                    field.SetDisplayType(displayType);
                }
                else
                {
                    VComboBox vcmb = new VComboBox(field.GetColumnName(), false, false, true, field.GetLookup(), 20);
                    ctrl = vcmb;
                }
            }
            else
            {
                //ctrl = VControlFactory.GetControl(field, false);
                ctrl = VControlFactory.GetControl(null, field, false, false, false);
            }
            ctrl.SetIsMandatory(false);
            // get label for the field
            VLabel label = VControlFactory.GetLabel(field);
            //
            if (displayLength > 0)		//	set it back
                field.SetDisplayLength(displayLength);

            _lineNo++;

            //Add new row

            tblpnlS.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });

            // display label for field
            if (label != null)	//	may be null for Y/N
            {
                //silver light comment
                //tblpnlS.Controls.Add(label, 0, _lineNo);
                //label.Anchor = AnchorStyles.Right;
                //label.AutoSize = true;
                tblpnlS.Children.Add(label);

                label.Margin = new Thickness(3);
                label.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
                Grid.SetColumn(label, 0);
                Grid.SetRow(label, tblpnlS.RowDefinitions.Count - 1);

            }

            if (ctrl != null)
            {
                // set width of the control
                ctrl.SetReadOnly(false);
                Control ct = (Control)ctrl;
               // ct.Width = 198;
                ct.IsEnabled = true;
                //ct.Anchor = ((AnchorStyles)((AnchorStyles.Left | AnchorStyles.Right)));//silverlight comment
                // add control in tablelayout panel
                //tblpnlS.Controls.Add(ct, 1, _lineNo);//silverlight comment
                tblpnlS.Children.Add(ct);
                ct.Margin = new Thickness(3);
                Grid.SetColumn(ct, 1);
                Grid.SetRow(ct, tblpnlS.RowDefinitions.Count - 1);
            }
            // add the control in list
            _sEditors.Add(ctrl);
        }

        /// <summary>
        /// requery
        /// </summary>
        private void Requery()
        {
            SetBusy(true);
            // save row
            SaveRowTemp();	//	unsaved 
            // get query
            Query temp = GetQueryAdvanced();
            int records = 0;
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                // get total records according to the query
                records = GetNoOfRecords(temp, true);
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => RecodsFromQuery(records));
            });


        }

        private void RecodsFromQuery(int records)
        {
            // set total no of records
            SetStatusDB(records);
            SetBusy(false);
            //CommonFunctions.ShowMessage("", lblStatusBar);
        }

        /// <summary>
        /// Opens for a new record
        /// </summary>
        private void NewRecord()
        {
            // set query
            _query = Query.GetNoRecordQuery(_tableName, true);
            _total = 0;
            _isOkPressed = true;
            _isOkButtonPressed = true;
            this.DialogResult = true;
        }
        #endregion

        #region "Second Tab Functions and Events"

        /// <summary>
        /// Save queries of Advanced tab
        /// </summary>
        private void SaveAdvanced()
        {
            // save all query lines temporarily
            SaveRowTemp();	//	unsaved 
            // get query
            _query = GetQueryAdvanced();
            if (_query.GetRestrictionCount() == 0)
            {
                SetBusy(false);
                return;
            }
            // get where clause
            string where = _query.GetWhereClause();
            // get query name entered by the user
            string name = vtxtQueryName.Text.Trim();
            if (name != null && name.Length == 0)
                name = null;
            // get the selected value
            object value = vcmbQueryA.SelectedValue;
            string s = "";// vcmbQueryA.Text;//silverlight comment
            //	Update Existing Query
            MUserQuery uq;

            String qMessage = "";


            BackgroundWorker bgw = new BackgroundWorker();

            bgw.DoWork += (sd, ed) =>
                {
                    if (value != null && value.ToString() != "0")
                    {
                        uq = new MUserQuery(_ctx, int.Parse(value.ToString()), null);
                        //set query name
                        if (name != null)
                            uq.SetName(name);
                        // set query code
                        uq.SetCode(where);
                        // set tab id
                        uq.SetAD_Tab_ID(_AD_Tab_ID);
                        // set table id
                        uq.SetAD_Table_ID(_AD_Table_ID);
                        // save the values in database
                        if (uq.Save())
                        {
                            // save the query lines of above saved query
                            Store(uq, dsAdvanceData);
                            _isSaveError = false;
                            //ShowMessage.Info("Updated", true, uq.GetName(), "");
                            qMessage = "Updated" + uq.GetName();

                            //MessageBox.Show("Updated" + uq.GetName());
                        }
                        else
                        {
                            _isSaveError = true;
                            //ShowMessage.Warn("SaveError", true, uq.GetName(), "");

                            qMessage = "UpdateError" + uq.GetName();
                           // MessageBox.Show("SaveError" + uq.GetName());
                        }
                    }
                    //	else Insert New Query
                    else if (name != null)
                    {
                        uq = new MUserQuery(_ctx, 0, null);
                        //set query name
                        uq.SetName(name);
                        // set query code
                        uq.SetCode(where);
                        // set tab id
                        uq.SetAD_Tab_ID(_AD_Tab_ID);
                        // set table id
                        uq.SetAD_Table_ID(_AD_Table_ID);
                        // save the values in database
                        if (uq.Save())
                        {
                            // save the query lines of above saved query
                            Store(uq, dsAdvanceData);
                            _isSaveError = false;
                            //ShowMessage.Info("Saved", true, uq.GetName(), "");
                            qMessage = "Saved" + uq.GetName();
                           // MessageBox.Show("Saved" + uq.GetName());

                        }
                        else
                        {
                            _isSaveError = true;
                            //ShowMessage.Warn("SaveError", true, uq.GetName(), "");
                            qMessage = "SaveError" + uq.GetName();
                           
                        }
                    }

                    ed.Result = false;
                    if (GetNoOfRecords(_query, true) != 0)
                    {
                        ed.Result = true;
                    }
                };

            bgw.RunWorkerCompleted += (sc, ec) =>
                {
                    SetBusy(false);

                    if (qMessage != "")
                    {
                        //MessageBox.Show(qMessage);
                        ShowMessage.Info(qMessage, true, "", null);
                    }

                    if (ec.Result != null && (bool)ec.Result)
                    {
                        closeMyWindow();
                    }
                    bgw = null;
                };

            bgw.RunWorkerAsync();
        }

        /// <summary>
        /// Get Query from Advanced Tab
        /// </summary>
        /// <returns>query</returns>
        private Query GetQueryAdvanced()
        {
            Query query = new Query(_tableName);
            // check if dataset have any table
            if (dsAdvanceData.Tables.Count == 1)
            {
                // for every row in dataset
                for (int i = 0; i < dsAdvanceData.Tables[0].Rows.Count; i++)
                {
                    DataRow dtRowObj = dsAdvanceData.Tables[0].Rows[i];
                    //	Column
                    string infoName = dtRowObj["KEYNAME"].ToString();
                    string columnName = dtRowObj["KEYVALUE"].ToString();
                    GridField field = GetTargetMField(columnName);
                    string columnSQL = field.GetColumnSQL(); //
                    //	Operator
                    string optr = dtRowObj["OPERATORNAME"].ToString(); //dtRowObj["OPERATOR"].ToString()
                    //	Value

                    object value = dtRowObj["VALUE1VALUE"];
                     object parsedValue = null;
                    if (value != null && value.ToString().Trim().StartsWith("adddays") || value.ToString().Trim().StartsWith("@"))
                    {
                        ;
                    }
                    else
                    {
                        parsedValue = ParseValue(field, value);
                    }
                    //string infoDisplay = dtRowObj["VALUE1NAME"].ToString();
                    String infoDisplay = null;

                    if (value == null || value.ToString().Length < 1)
                    {
                        if (Query.BETWEEN.Equals(optr))
                            continue;	//	no null in between
                        parsedValue = Null.NULLString;
                        infoDisplay = "NULL";
                    }
                    else
                    {
                        infoDisplay = dtRowObj["VALUE1NAME"].ToString();
                    }

                    //	Value2
                    // if "BETWEEN" selected
                    if (Query.BETWEEN.Equals(optr))
                    {

                        object value2 = dtRowObj["VALUE2VALUE"].ToString();
                        if (value2 == null || value2.ToString().Trim().Length < 1)
                            continue;

                        Object parsedValue2 = ParseValue(field, value2);
                        string infoDisplay_to = dtRowObj["VALUE2NAME"].ToString();
                        if (parsedValue2 == null)
                            continue;
                        // else add restriction where clause to query with between operator
                        query.AddRangeRestriction(columnSQL, parsedValue, parsedValue2, infoName,
                            infoDisplay, infoDisplay_to);
                    }
                    else
                    {
                        // else add simple restriction where clause to query

                        if (parsedValue == null && value != null && (value.ToString().Trim().StartsWith("adddays") || value.ToString().Trim().StartsWith("@")))
                        {
                            string Where = columnName + optr + value;
                            Where = Envs.ParseContext(_ctx, 0, Where, false);
                            query.AddRestriction(Where);  
                        }
                        else
                        {
                            query.AddRestriction(columnSQL, optr, parsedValue, infoName, infoDisplay);
                        }
                    }
                }
            }
            return query;
        }

        /**
	 * 	Parse Value
	 * 	@param field column
	 * 	@param in value
	 * 	@return data type corrected value
	 */
        private Object ParseValue(GridField field, object pp)
        {
            if (pp == null)
                return null;
            int dt = field.GetDisplayType();
            String inStr = pp.ToString();
            if (inStr == null || inStr.Equals(Null.NULLString) || inStr == "")
                return null;
            try
            {
                //	Return Integer
                if (dt == DisplayType.Integer
                    || (DisplayType.IsID(dt) && field.GetColumnName().EndsWith("_ID")))
                {
                    int i = int.Parse(inStr);
                    return i;
                }
                //	Return BigDecimal
                else if (DisplayType.IsNumeric(dt))
                {
                    return Decimal.Parse(inStr);       //DisplayType.GetNumberFormat(dt).GetFormatedValue(inStr);
                }
                //	Return Timestamp
                else if (DisplayType.IsDate(dt))
                {
                    String time = "";
                    try
                    {
                        return DateTime.Parse(inStr);
                    }
                    catch (Exception e)
                    {
                        log.Log(Level.WARNING, inStr + "(" + inStr.GetType().FullName + ")" + e);
                        time = DisplayType.GetDateFormat(dt).Format(inStr);
                    }
                    try
                    {
                        return DateTime.Parse(time);
                    }
                    catch
                    {
                        return null;
                    }
                }
            }
            catch (Exception ex)
            {
                log.Log(Level.WARNING, "Object=" + inStr, ex);
                String error = ex.Message;
                if (error == null || error.Length == 0)
                    error = ex.ToString();
                StringBuilder errMsg = new StringBuilder();
                errMsg.Append(field.GetColumnName()).Append(" = ").Append(inStr).Append(" - ").Append(error);
                //
                //if(pp != null && pp.ToString().Trim().StartsWith("adddays") || pp.ToString().Trim().StartsWith("adddays")
                ShowMessage.Error("ValidationError", true, errMsg.ToString());
                //MessageBox.Show("ValidationError " + errMsg.ToString());
                return null;
            }

            return inStr;
        }	//	parseValue

        /// <summary>
        /// Gives the field object of given column name
        /// </summary>
        /// <param name="columnName">column name</param>
        /// <returns>field object</returns>
        private GridField GetTargetMField(string columnName)
        {
            // if no column name, then return null
            if (columnName == null)
                return null;
            // else find field for the given column
            for (int c = 0; c < _findFields.Length; c++)
            {
                GridField field = _findFields[c];
                if (columnName.Equals(field.GetColumnName()))
                    return field;
            }
            return null;
        }

        /// <summary>
        /// Bind grid to given dataset
        /// </summary>
        /// <param name="ds">dataset</param>
        private void BindGrid(DataSet ds)
        {
            // clear and unbind the grid
            vdgvQuery.DataContext = null;
            vdgvQuery.ItemsSource = null;
            //vdgvQuery.DataBindings.Clear();
            vdgvQuery.Columns.Clear();
            vdgvQuery.AutoGenerateColumns = false;

            //1. "Column" Column KEYNAME
            DataGridTextColumn columnObj = new DataGridTextColumn();
            columnObj.Header = Msg.Translate(_ctx, "AD_Column_ID");
            columnObj.Binding = new System.Windows.Data.Binding("KEYNAME");
            columnObj.IsReadOnly = true;
            vdgvQuery.Columns.Add(columnObj);

            //2. "Column" Column KEYVALUE
            DataGridTextColumn keyvalueObj = new DataGridTextColumn();
            keyvalueObj.Header = Msg.Translate(_ctx, "KEYVALUE");
            keyvalueObj.Binding = new System.Windows.Data.Binding("KEYVALUE");
            keyvalueObj.IsReadOnly = true;
            vdgvQuery.Columns.Add(keyvalueObj);


            //3. "Operator" Column OPERATORNAME
            DataGridTextColumn opNameObj = new DataGridTextColumn();
            opNameObj.Header = Msg.Translate(_ctx, "OperatorName");
            opNameObj.Binding = new System.Windows.Data.Binding("OPERATORNAME");
            opNameObj.IsReadOnly = true;
            vdgvQuery.Columns.Add(opNameObj);



            //4. "Query Value" Column VALUE1NAME
            DataGridTextColumn valueObj = new DataGridTextColumn();
            valueObj.Header = Msg.Translate(_ctx, "QueryValue");
            valueObj.Binding = new System.Windows.Data.Binding("VALUE1NAME");
            valueObj.IsReadOnly = true;
            vdgvQuery.Columns.Add(valueObj);

            //5. "VALUE1VALUE" Column VALUE1VALUE
            DataGridTextColumn value1Obj = new DataGridTextColumn();
            value1Obj.Header = Msg.Translate(_ctx, "VALUE1VALUE");
            value1Obj.Binding = new System.Windows.Data.Binding("VALUE1VALUE");
            value1Obj.IsReadOnly = true;
            vdgvQuery.Columns.Add(value1Obj);

            //6. "VALUE2NAME" Column VALUE2NAME
            DataGridTextColumn value2Obj = new DataGridTextColumn();
            value2Obj.Header = Msg.Translate(_ctx, "QueryValue2");
            value2Obj.Binding = new System.Windows.Data.Binding("VALUE2NAME");
            value2Obj.IsReadOnly = true;
            vdgvQuery.Columns.Add(value2Obj);

            //7. "VALUE2VALUE" Column VALUE2VALUE
            DataGridTextColumn valueVObj = new DataGridTextColumn();
            valueVObj.Header = Msg.Translate(_ctx, "VALUE2VALUE");
            valueVObj.Binding = new System.Windows.Data.Binding("VALUE2VALUE");
            valueVObj.IsReadOnly = true;
            vdgvQuery.Columns.Add(valueVObj);

            //8. "AD_USERQUERYLINE_ID" Column AD_USERQUERYLINE_ID
            DataGridTextColumn idObj = new DataGridTextColumn();
            idObj.Header = Msg.Translate(_ctx, "AD_USERQUERYLINE_ID");
            idObj.Binding = new System.Windows.Data.Binding("AD_USERQUERYLINE_ID");
            idObj.IsReadOnly = true;
            vdgvQuery.Columns.Add(idObj);

            //9. "Operator" Column OPERATOR
            DataGridTextColumn opObj = new DataGridTextColumn();
            opObj.Header = Msg.Translate(_ctx, "Operator");
            opObj.Binding = new System.Windows.Data.Binding("OPERATOR");
            opObj.IsReadOnly = true;
            vdgvQuery.Columns.Add(opObj);

            ///DataGridBoundColumn bc = new DataGridBoundColumn();
            Grids.DataGridImageColumn img = new DataGridImageColumn();
            img.Image = Envs.LoadImageSource("delete.png");
            
            img.Header = "Action";

            img.Click += new RoutedEventHandler(img_Click);
            //10. "Delete" Column
           // DataGridTemplateColumn deleteObj = new DataGridTemplateColumn();
           // deleteObj.Header = "Action";

           // deleteObj.CellTemplate = new DataTemplate() {    (DataTemplate)Resources["myCellTemplate"];
           // deleteObj.CellEditingTemplate = (DataTemplate)Resources["myCellEditingTemplate"];

           //// using xml reader
           // //deleteObj.CellTemplate = (DataTemplate)XamlReader.Load("<DataTemplate><Image Source=/MySilverlightApp;component/images/ExportToClientX24.png/></DataTemplate>");
            vdgvQuery.Columns.Add(img);

            // if user has given any dataset
            if (ds != null)
            {
                // bind grid to dataset values
                vdgvQuery.ItemsSource = ds.Tables[0].GetBindableData(new Connector());// GenerateData(ds).ToDataSource();
                //vdgvQuery.ItemsSource = ds.Tables[0].GetBindableData(new Connector());  //set the data source of the objet to ds
            }
            vdgvQuery.Columns[1].Visibility = System.Windows.Visibility.Collapsed;//"KEYVALUE"
            vdgvQuery.Columns[4].Visibility = System.Windows.Visibility.Collapsed;//"VALUE1VALUE"
            vdgvQuery.Columns[6].Visibility = System.Windows.Visibility.Collapsed;//"VALUE2VALUE"
            vdgvQuery.Columns[7].Visibility = System.Windows.Visibility.Collapsed;//"AD_USERQUERYLINE_ID"
            vdgvQuery.Columns[8].Visibility = System.Windows.Visibility.Collapsed;//"OPERATOR"


        }

        void img_Click(object sender, RoutedEventArgs e)
        {
            int index = vdgvQuery.SelectedIndex;
            if (index > -1)
            {
                dsAdvanceData.Tables[0].Rows.RemoveAt(index);
                BindGrid(dsAdvanceData);
            }
        }

        private void AddRow(string colName, string colValue, string optr, string optrName,
          string value1Name, object value1Value, string value2Name, object value2Value)
        {
            
            if (dsAdvanceData.Tables.Count == 0)
            {
                DataTable dt = new DataTable();
                //if dataset has no table, the add a table and columns in it
                //dsAdvanceData.Tables.Add();iam creating colum first then add it to table//silverlight comment

                DataColumn dc;
                dc = new DataColumn("KEYNAME");
                dt.Columns.Add(dc);
                //dsAdvanceData.Tables[0].Columns.Add(dc);
                dc = new DataColumn("KEYVALUE");
                dt.Columns.Add(dc);
                //dsAdvanceData.Tables[0].Columns.Add(dc);
                dc = new DataColumn("OPERATORNAME");
                dt.Columns.Add(dc);
                //dsAdvanceData.Tables[0].Columns.Add(dc);
                dc = new DataColumn("VALUE1NAME");
                dt.Columns.Add(dc);
                //dsAdvanceData.Tables[0].Columns.Add(dc);
                dc = new DataColumn("VALUE1VALUE");
                dt.Columns.Add(dc);
                //dsAdvanceData.Tables[0].Columns.Add(dc);
                dc = new DataColumn("VALUE2NAME");
                dt.Columns.Add(dc);
                //dsAdvanceData.Tables[0].Columns.Add(dc);
                dc = new DataColumn("VALUE2VALUE");
                dt.Columns.Add(dc);
                //dsAdvanceData.Tables[0].Columns.Add(dc);
                dc = new DataColumn("AD_USERQUERYLINE_ID");
                dt.Columns.Add(dc);
                //dsAdvanceData.Tables[0].Columns.Add(dc);
                dc = new DataColumn("OPERATOR");
                //dsAdvanceData.Tables[0].Columns.Add(dc);//silverlight comment
                dt.Columns.Add(dc);
                dsAdvanceData.Tables.Add(dt);
            }


            // new row
            DataRow dr = dsAdvanceData.Tables[0].NewRow();
            // set values in new row
            dr[0] = colName;
            dr[1] = colValue;
            dr[2] = optrName;
            dr[3] = value1Name;
            if (value1Name == "")
                dr[4] = "";
            else
            {
                if (value1Value == null)
                    dr[4] = "NULL";
                else
                    dr[4] = Util.GetValueOfString(value1Value);
            }
            dr[5] = value2Name;
            //dr[6] = value2Value;
            if (value2Value == null)
                dr[6] = "NULL";
            else
                dr[6] = Util.GetValueOfString(value2Value);
            dr[7] = "0";
            dr[8] = optr;
            dsAdvanceData.Tables[0].Rows.Add(dr);
            // add row in dataset
            //dsAdvanceData.Tables[0].Rows.Add(dr);//silverlight comment If i add like wiundow it show row count=2
            // bind grid

            BindGrid(dsAdvanceData);//for the time beeing commented today 3Dec.2010
            /***************************************/

            //vdgvQuery.ItemsSource = null;
            //vdgvQuery.Columns.Clear();
            //vdgvQuery.AutoGenerateColumns = true;
            //vdgvQuery.ItemsSource = GenerateData2(dsAdvanceData).ToDataSource();
            //vdgvQuery.IsReadOnly = true;

            //vdgvQuery.Columns[1].Visibility = System.Windows.Visibility.Collapsed;//"KEYVALUE"
            //vdgvQuery.Columns[4].Visibility = System.Windows.Visibility.Collapsed;//"VALUE1VALUE"
            //vdgvQuery.Columns[6].Visibility = System.Windows.Visibility.Collapsed;//"VALUE2VALUE"
            //vdgvQuery.Columns[7].Visibility = System.Windows.Visibility.Collapsed;//"AD_USERQUERYLINE_ID"
            //vdgvQuery.Columns[8].Visibility = System.Windows.Visibility.Collapsed;//"OPERATOR"

            ////create grid image column for grid
            //DataGridTemplateColumn deleteObj = new DataGridTemplateColumn();
            //deleteObj.Header = "Action";
            //deleteObj.CellTemplate = this.Resources["Copy16.jpg"] as DataTemplate;
            ////deleteObj.CellTemplate = (DataTemplate)XamlReader.Load("<DataTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"><Image Source=\"Images/Copy16.jpg\"/></DataTemplate>");
            //// myTemplateColumn.CellTemplate = (DataTemplate)XamlReader.Load("<DataTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"><Image Source=\"http://diditwith.net/content_images/Dog_With_Santa.jpg\"/></DataTemplate>");
            //vdgvQuery.Columns.Add(deleteObj);

            /***************************************/

        }
        public IEnumerable<IDictionary> GenerateData1(DataSet ds)
        {
            if (ds == null)
            {
               // log.Log(Level.SEVERE, dataSql, "");
            }
            else
            {
                for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
                {
                    int colOffset = 0;  //  columns start with 1
                    var dict = new Dictionary<string, object>();
                    for (int col = 0; col < ds.Tables[0].Columns.Count; col++)
                    {
                        Object data = null;
                        Type c = ds.Tables[0].Columns[col].GetType();// GetColClass();
                        int colIndex = col + colOffset;

                        String colName = ds.Tables[0].Columns[col].ColumnName;//_Layout[col].GetColHeader();
                        if (c == typeof(IDColumn))
                        {
                            data = new IDColumn(Util.GetValueOfInt(ds.Tables[0].Rows[i][colIndex].ToString()));
                        }
                        else if (c == typeof(Boolean))
                        {
                            Object bl = ds.Tables[0].Rows[i][colIndex];
                            if (bl == null)
                                data = false;
                            else
                                data = "Y".Equals(bl.ToString());
                        }
                        else if (c == typeof(DateTime))
                        {
                            if (ds.Tables[0].Rows[i][colIndex] == null)
                                data = "";
                            else
                            {
                                if (ds.Tables[0].Rows[i][colIndex].ToString() != "")
                                {
                                    data = DateTime.Parse(ds.Tables[0].Rows[i][colIndex].ToString());
                                }
                                else
                                {
                                    data = "";
                                }
                            }
                        }
                        else if (c == typeof(Decimal))
                        {
                            data = Util.GetValueOfDecimal(ds.Tables[0].Rows[i][colIndex].ToString());
                        }
                        else if (c == typeof(Double))
                        {
                            data = Util.GetValueOfDecimal(ds.Tables[0].Rows[i][colIndex].ToString());
                        }
                        else if (c == typeof(Int32))
                        {
                            data = Util.GetValueOfInt(ds.Tables[0].Rows[i][colIndex].ToString());
                        }
                        else if (c == typeof(KeyNamePair))
                        {
                            Object display = null;
                            if (ds.Tables[0].Rows[i][colIndex] != null)
                                display = ds.Tables[0].Rows[i][colIndex].ToString();
                            else
                                display = "";

                            int KeyValue = ds.Tables[0].Rows[i][colIndex + 1] == null ? 0 : Util.GetValueOfInt(ds.Tables[0].Rows[i][colIndex + 1].ToString());
                            int key = display != "" ? KeyValue : 0;
                            data = new KeyNamePair(key, display.ToString());
                            colOffset++;
                        }
                        else
                        {
                            if (ds.Tables[0].Rows[i][colIndex] != null)
                                data = ds.Tables[0].Rows[i][colIndex].ToString();
                            else
                                data = "";
                        }

                        dict[colName] = data;       //finally add data to enumerable dictionary

                    }

                    yield return dict;
                }
            }
        }

        public IEnumerable<IDictionary> GenerateData(DataSet ds)
        {
            if (ds == null)
            {
                //log.Log(Level.SEVERE, dataSql, "");
            }
            else
            {
                for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
                {
                    var dict = new Dictionary<string, object>();
                    for (int col = 0; col < ds.Tables[0].Columns.Count; col++)
                    {
                        Object data = null;
                        String colName = ds.Tables[0].Columns[col].ColumnName;//_Layout[col].GetColHeader();
                        if (ds.Tables[0].Rows[i][col] != null)
                        {
                            data = ds.Tables[0].Rows[i][col].ToString();
                        }
                        else
                        {
                            data = "";
                        }
                        dict[colName] = data;       //finally add data to enumerable dictionary
                    }

                    yield return dict;
                }
            }
        }

        public IEnumerable<IDictionary> GenerateData2(DataSet ds)
        {
            for (var i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                var dict = new Dictionary<string, object>();
                dict["AD_Column_ID"] = ds.Tables[0].Rows[i][0];//KEYNAME
                dict["OPERATORNAME"] = ds.Tables[0].Rows[i][2];
                dict["QueryValue"] = ds.Tables[0].Rows[i][3];//VALUE1NAME
                dict["QueryValue2"] = ds.Tables[0].Rows[i][5];//VALUE2NAME

                dict["KEYVALUE"] = ds.Tables[0].Rows[i][1];
                dict["VALUE1VALUE"] = ds.Tables[0].Rows[i][4];
                dict["VALUE2VALUE"] = ds.Tables[0].Rows[i][6];
                dict["AD_USERQUERYLINE_ID"] = ds.Tables[0].Rows[i][7];
                dict["OPERATOR"] = ds.Tables[0].Rows[i][8];
                yield return dict;
            }
        }
        /// <summary>
        /// Save row temporarily
        /// </summary>
        /// <returns>Bool type-true if record saved succcessfuly</returns>
        private bool SaveRowTemp()
        {
            // set column name
            if (vcmbColumn.SelectedItem == null)
                return false;

            string colName = ((System.Data.BindableObject)vcmbColumn.SelectedItem).GetValue("Name"); // vcmbColumn.Text;//silverlight comment
            string colValue = "";
            if (colName == null || colName.Trim().Length == 0)
            {
                return false;
            }
            else
            {
                // set column value
                colValue = vcmbColumn.SelectedValue.ToString();
            }

            if (chkDynamic.IsChecked.Value)
            {
                

                if (cmbDymamicValue.Visibility == System.Windows.Visibility.Visible)
                {
                    string opValueD = ">=";
                    string opNameD = " >= ";
                    string controlText = cmbDymamicValue.GetText(cmbDymamicOp.SelectedIndex);
                    string controlValue = cmbDymamicValue.GetValue(cmbDymamicOp.SelectedIndex);
                    AddRow(colName, colValue, opNameD, opValueD, controlText, controlValue, null, null);
                }
                else
                {
                    string opValueD = "=";
                    string opNameD = " = ";
                    string controlText = ((System.Data.BindableObject)cmbDymamicOp.SelectedItem).GetValue("Name");
                    string controlValue = ((System.Data.BindableObject)cmbDymamicOp.SelectedItem).GetValue("Value");
                    //string controlValue = cmbDymamicValue.GetValue(cmbDymamicOp.SelectedIndex);
                    AddRow(colName, colValue, opNameD, opValueD, controlText, controlValue, null, null);
                }
            }
            else
            {

                // set operator name
                string opName = "";
                if (vcmbOperator.SelectedItem != null)
                    opName = ((System.Data.BindableObject)vcmbOperator.SelectedItem).GetValue("Name"); ;// vcmbOperator.Text;//silverlight comment
                // set operator (sign)
                string opValue = vcmbOperator.SelectedValue.ToString();
                // add row in dataset
                AddRow(colName, colValue, opName, opValue, GetControlText(true), GetControlValue(true), GetControlText(false), GetControlValue(false));
            }
            //reset column & operator comboBox
            vcmbColumn.SelectedIndex = 0;
            vcmbOperator.SelectedIndex = 0;
            SetControlNullValue();
            //silverlight comment
            // SetControl(false, null);
            vtxtQueryName.IsEnabled = true;

            return true;
        }

        /// <summary>
        /// Load data in Advanced tab
        /// </summary>
        private void InitFindAdvanced()
        {
            dsAdvanceData = new DataSet();
            // empty the grid
            BindGrid(null);
            // disbale delete query button
            SetEnableButton(ibtnDelQuery, false);//silverlight comment
            // get headers text
            _gridColHead = Msg.Translate(_ctx, "AD_Column_ID");
            _gridOptrHead = Msg.Translate(_ctx, "Operator");
            _gridValue1Head = Msg.Translate(_ctx, "QueryValue");
            _gridValue2Head = Msg.Translate(_ctx, "QueryValue2");

            // FillQuery();

            // set headers text in labels
            vlblColName.Content = _gridColHead;
            vlblOperator.Content = _gridOptrHead;
            vlblValue.Content = _gridValue1Head;
            vlblValue2.Content = _gridValue2Head;

            vlblQueryName.Content = Msg.GetMsg(Envs.GetContext(), "SaveQuery", true);
            vlblSelectQuery.Content = Msg.GetMsg(Envs.GetContext(), "GetSavedQuery", true);

            // set all combobox properties
            // set datagrid properties
            //CommonFunctions.SetDataGridPrperties(vdgvQuery);//silverlight comment
            // fill all the columns in whole of grid
            //vdgvQuery.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;//silverlight comment

            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                DataSet dsQueries = MUserQuery.GetDataSet(_ctx, _AD_Tab_ID, _AD_Table_ID, "AD_UserQuery_ID");
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => FillCombo(vcmbQueryA, "Name", "AD_UserQuery_ID", dsQueries));
                // create a datatable and its columns
                DataTable dt = new DataTable("Items");
                DataColumn dc;
                DataRow dr;
                dc = new DataColumn("Name");
                dt.Columns.Add(dc);
                dc = new DataColumn("Value");
                dt.Columns.Add(dc);

                dr = dt.NewRow();
                dr[0] = " " ; // Name
                dr[1] = ""; // DB
                dt.Rows.Add(dr);
                // for each field
                for (int c = 0; c < _findFields.Length; c++)
                {
                    // get field
                    GridField field = _findFields[c];
                    if (field.IsEncrypted())
                        continue;
                    // get field's column name
                    string columnName = field.GetColumnName();
                    if (field.GetDisplayType() == DisplayType.Button)
                    {
                        if (field.GetAD_Reference_Value_ID() == 0)
                            continue;
                        if (columnName.EndsWith("_ID"))
                            field.SetDisplayType(DisplayType.Table);
                        else
                            field.SetDisplayType(DisplayType.List);
                        field.LoadLookUp();
                    }
                    // get text to be displayed
                    string header = field.GetHeader();
                    if (header == null || header.Length == 0)
                    {
                        // get text according to the language selected
                        header = Msg.GetElement(_ctx, columnName);
                        if (header == null || header.Length == 0)
                            continue;
                    }
                    // if given field is any key, then add "(ID)" to it
                    if (field.IsKey())
                        header += (" (ID)");

                    // add a new row in datatable and set values
                    dr = dt.NewRow();
                    dr[0] = header; // Name
                    dr[1] = columnName; // DB_ColName
                    dt.Rows.Add(dr);

                }
                // add above datatable to dataset
                DataSet ds = new DataSet();
                ds.Tables.Add(dt);
                // fill combobox with query names
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(delegate { FillCombo(vcmbColumn, "Name", "Value", ds); SetBusy(false); });
            });

            //enable operator combobox
            vcmbOperator.IsEnabled = false;
            // display an empty disabled textbox at value1 and value2 positions
            SetControl(true, null);
            SetControl(false, null);
            //objective of this line is get at design time
            //

            // disable save button
             SetEnableButton(ibtnSaveRow, false);//silverlight comment
        }

        /// <summary>
        /// Fills Query combox with query names
        /// </summary>
        private void FillQuery()
        {
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                // fill combobox with query names
                DataSet dsQueries = MUserQuery.GetDataSet(_ctx, _AD_Tab_ID, _AD_Table_ID, "AD_UserQuery_ID");
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(delegate { FillCombo(vcmbQueryA, "Name", "AD_UserQuery_ID", dsQueries); vcmbQueryA.SelectedIndex = vcmbQueryA.Items.Count - 1; });
            });
        }

        List<KeyNamePair> ListQueries = new List<KeyNamePair>();
        private void FillCombo(VComboBox cmbCtl, string name, string value, DataSet dsQueries)
        {
            

            //silverlight comment
            Common.FillCombo.Fill(cmbCtl, name, value, dsQueries);
            //FillCombo.Fill(vcmbQueryA, "Name", "AD_UserQuery_ID", dsQueries, true, "");//silverlight comment
        }
       
        private ObservableCollection<KeyNamePair> ComboList()
        {
            ObservableCollection<KeyNamePair> list = new ObservableCollection<KeyNamePair>();
            list.Add(new KeyNamePair(0, Msg.GetMsg(Envs.GetContext(), "All", true)));
            list.Add(new KeyNamePair(365, Msg.GetMsg(Envs.GetContext(), "YearAll", true)));
            list.Add(new KeyNamePair("365 | C", Msg.GetMsg(Envs.GetContext(), "YearCreated", true)));
            list.Add(new KeyNamePair(31, Msg.GetMsg(Envs.GetContext(), "MonthAll", true)));
            list.Add(new KeyNamePair("31 | C", Msg.GetMsg(Envs.GetContext(), "MonthCreated", true)));
            list.Add(new KeyNamePair(7, Msg.GetMsg(Envs.GetContext(), "WeekAll", true)));
            list.Add(new KeyNamePair("7 | C", Msg.GetMsg(Envs.GetContext(), "WeekCreated", true)));
            list.Add(new KeyNamePair(1, Msg.GetMsg(Envs.GetContext(), "DayAll", true)));
            list.Add(new KeyNamePair("1 | C", Msg.GetMsg(Envs.GetContext(), "DayCreated", true)));
            return list;
        }

        /// <summary>
        /// Returns the dataset from valuenamepair given
        /// </summary>
        /// <param name="vnpObj">ValueNamePair array</param>
        /// <returns>Dataset of operators</returns>
        private DataSet GetOperatorsQuery(ValueNamePair[] vnpObj)
        {
            DataSet ds = new DataSet();
            //ds.Tables.Add("Oper");
            // add the columns in dataset
            //ds.Tables[0].Columns.Add("Name");
            //ds.Tables[0].Columns.Add("Value");
            DataTable dt = new DataTable();
            dt.Columns.Add(new DataColumn("Name"));
            dt.Columns.Add(new DataColumn("Value"));
            ds.Tables.Add(dt);
            ValueNamePair val;
            DataRow dr = null;
            for (int i = 0; i < vnpObj.Length; i++)
            {
                val = vnpObj[i];
                // add a new row
                dr = ds.Tables[0].NewRow();
                // set values
                dr[1] = val.GetValue(); // text
                dr[0] = val.GetName(); // signs
                //add row in dataset
                ds.Tables[0].Rows.Add(dr);
            }
            return ds;
        }

        //private void vtabLookup_Deselecting(object sender, TabControlCancelEventArgs e)
        //{
        //    if (vtabLookup.SelectedIndex == 0) // if 1st tab is being deselected
        //    {
        //        InitFindAdvanced();
        //    }
        //}

        /// <summary>
        /// Enable/Diable control at value2 position
        /// </summary>
        /// <param name="isEnabled">true if want to set enabled</param>
        private void SetValue2Enabled(bool isEnabled)
        {
            // get control
            Control crtlObj = (Control)GetControlFromPosition(2, 3);// tblpnlA2.GetControlFromPosition(3, 1);
            // if control exists
            if (crtlObj != null)
            {
                crtlObj.IsEnabled = isEnabled;
            }
        }

        /// <summary>
        /// Enable/Diable control at value1 position
        /// </summary>
        /// <param name="isEnabled">true if want to set enabled</param>
        private void SetValueEnabled(bool isEnabled)
        {
            // get control
            //Control crtlObj = tblpnlA2.GetControlFromPosition(2, 1);
            Control crtlObj = (Control)GetControlFromPosition(2, 2);
            // if control exists
            if (crtlObj != null)
            {
                crtlObj.IsEnabled = isEnabled;
            }
        }

        /// <summary>
        /// Gets control's value
        /// </summary>
        /// <param name="isValue1">true if get control's text at value1 position else false</param>
        /// <returns>text of control</returns>
        private object GetControlValue(bool isValue1)
        {
            IControl crtlObj = null;
            // get control
            if (isValue1)
            {
                // crtlObj = (IControl)tblpnlA2.GetControlFromPosition(2, 1);
                crtlObj = GetControlFromPosition(2, 2);
            }
            else
            {
                //  crtlObj = (IControl)tblpnlA2.GetControlFromPosition(3, 1);
                crtlObj = GetControlFromPosition(2, 3);
            }
            // if control exists
            if (crtlObj != null)
            {
                // if control is any checkbox
                if (crtlObj.GetDisplayType() == DisplayType.YesNo)
                {
                    // if checkbox is selected
                    if (crtlObj.GetValue().ToString().ToLower() == "true")
                    {
                        return "Y";
                    }
                    else
                    {
                        return "N";
                    }
                }
                // return control's value
                return crtlObj.GetValue();
            }
            return "";
        }

        /// <summary>
        /// Gets control text
        /// </summary>
        /// <param name="isValue1">true if get control's text at value1 position else false</param>
        /// <returns>text of control</returns>
        private string GetControlText(bool isValue1)
        {
            IControl crtlObj = null;
            // get control
            if (isValue1)
            {
                // crtlObj = (IControl)tblpnlA2.GetControlFromPosition(2, 1);
                crtlObj = GetControlFromPosition(2, 2);
            }
            else
            {
                // crtlObj = (IControl)tblpnlA2.GetControlFromPosition(3, 1);
                crtlObj = GetControlFromPosition(2, 3);
            }
            // if control exists
            if (crtlObj != null)
            {
                // get control's text
                return crtlObj.GetText();
            }
            return "";
        }
        private IControl GetControlFromPosition(int row, int col)
        {
            IControl crtlObj = null;
            /*****Get control form specified column and row from Grid***********/
            var eList = from child in tblpnlA.Children
                        where Grid.GetRow((FrameworkElement)child) == row && Grid.GetColumn((FrameworkElement)child) == col
                        select child;

            //Remove any elements in the list
            while (eList.Count() > 0)
            {
                crtlObj = (IControl)eList.First();
                break;
            }
            /**********************************/
            return crtlObj;
        }


        /// <summary>
        /// Sets null value of the control
        /// </summary>
        private void SetControlNullValue()
        {
            IControl crtlObj = null;
            /*****Get control form specified column and row from Grid***********/
            var eList = from child in tblpnlA.Children
                        where Grid.GetRow((FrameworkElement)child) == 2 && Grid.GetColumn((FrameworkElement)child) == 2
                        select child;

            //Remove any elements in the list
            while (eList.Count() > 0)
            {
                crtlObj = (IControl)eList.First();
                break;
            }
            /**********************************/
            // if control exists
            if (crtlObj != null)
            {
                crtlObj.SetValue(null);
            }


        }

        /// <summary>
        /// Sets a control for value1 or value2
        /// </summary>
        /// <param name="isValue1">true if set control at value1 position else false</param>
        /// <param name="field">field object</param>
        private void SetControl(bool isValue1, GridField field)
        {
            // set column and row position
            int col = 0;
            int row = 2;
            if (isValue1)
            {
                col = 2;
            }
            else
            {
                col = 3;
            }

            /*****Get control form specified column and row from Grid***********/
            var eList = from child in tblpnlA.Children
                        where Grid.GetRow((FrameworkElement)child) == row && Grid.GetColumn((FrameworkElement)child) == col
                        select child;

            //Remove any elements in the list
            if (eList.Count() > 0)
            {
                Control c = (Control)eList.First();

                
                tblpnlA.Children.Remove(c);

                Grid.SetColumn(c, 111);
                Grid.SetRow(c, 111);
                if (c is IControl)
                {
                    //((IControl)c).Dispose();
                }
                c = null;
            }
            /**********************************/
            IControl crt = null;
            // if any filed is given
            if (field != null)
            {
                // if field id any key, then show number textbox 
                if (field.IsKey())
                {
                    crt = new VAdvantage.Controls.VNumTextBox(field.GetColumnName(), false, false, true,
                                    DisplayType.Integer, field.GetColumnName());
                }
                else
                {
                    crt = VControlFactory.GetControl(null, field, true, true, false);
                }
            }
            else
            {
                // if no field is given show an empty disabled textbox
                crt = new VAdvantage.Controls.VTextBox("columnName", false, true, false, 20, 20, "format",
                          "GetObscureType", VAdvantage.Controls.VTextBox.TextType.Text, DisplayType.String);

            }
            if (crt != null)
            {
                //crt.SetIsMandatory(false);
                crt.SetReadOnly(false);
                if (crt is Control)
                {
                    // crt.SetReadOnly(false);
                    ((Control)crt).IsEnabled = true;
                }
                //set the control's width
                Control c = (Control)crt;

                if (crt.GetDisplayType() != DisplayType.YesNo)
                {
                    //c.Width = 132;
                    c.Height = 23;
                }
                else
                {
                   // c.Width = 15;
                    c.Height = 23;
                }

                Grid.SetRow(c, row);
                Grid.SetColumn(c, col);

                c.Margin = new Thickness(2);

                this.tblpnlA.Children.Add(c);
            }
        }

        /// <summary>
        /// Add a row in dataset
        /// </summary>
        /// <param name="colName">column Name(Key name)</param>
        /// <param name="colValue">column Value(Key Value)</param>
        /// <param name="opName">operator name</param>
        /// <param name="opValue">operator value(sign)</param>
        /// <param name="value1Name">query value text</param>
        /// <param name="value1Value">query value's value</param>
        /// <param name="value2Name">"to query value" text</param>
        /// <param name="value2Value">"to query value's" value</param>



        private void chkDynamic_CheckedChanged(object sender, RoutedEventArgs e)
        {
            if ((bool)chkDynamic.IsChecked)
            {
                vcmbOperator.IsEnabled = false;
                SetValueEnabled(false);
                SetValue2Enabled(false);
                Grid.SetRow(ibtnSaveRow, 3);
            }
            else
            {
                vcmbOperator.IsEnabled = true;
                SetValueEnabled(true);
                SetValue2Enabled(true);
                Grid.SetRow(ibtnSaveRow, 2);
            }

        }

        //private void vdgvQuery_CellClick(object sender, DataGridViewCellEventArgs e)
        //{
        //    // if user clicks on Delete button of grid
        //    if (vdgvQuery.Columns["Delete"].Index == e.ColumnIndex)
        //    {
        //        // remove the selected row from dataset
        //        int rowIndex = e.RowIndex;
        //        if (rowIndex == -1)
        //        {
        //            return;
        //        }
        //        dsAdvanceData.Tables[0].Rows.RemoveAt(rowIndex);
        //        //BindGrid(dsAdvanceData);
        //    }
        //}

        /// <summary>
        /// Store and Save Query Lines
        /// </summary>
        /// <param name="query">query</param>
        /// <param name="dsObj">dataset whose rows are to be saved</param>
        /// <returns>Bool type-true if saved</returns>
        private bool Store(MUserQuery query, DataSet dsObj)
        {
            // delete existing query lines
            query.DeleteLines();
            // if no lines then return
            if (dsObj == null)
            {
                return true;
            }
            int totCnt = dsObj.Tables[0].Rows.Count;
            // save each the query lines in the dataset
            for (int i = 0; i < totCnt; i++)
            {
                DataRow dtRowObj = dsObj.Tables[0].Rows[i];
                //object[] dtRowObj1 = dsObj.Tables[0].Rows[i].ItemArray;
                //if (dtRowObj["VALUE1NAME"].ToString() != "")
                {
                    // set values
                    MUserQueryLine line = new MUserQueryLine(query, (i + 1) * 10, dtRowObj["KEYNAME"].ToString(),
                        dtRowObj["KEYVALUE"].ToString(), dtRowObj["OPERATORNAME"].ToString(),
                        dtRowObj["VALUE1NAME"].ToString(), dtRowObj["VALUE1VALUE"].ToString(),
                        dtRowObj["VALUE2NAME"].ToString(), dtRowObj["VALUE2VALUE"].ToString());
                    // save query line
                    line.Save();
                }
            }
            return true;
        }

        /// <summary>
        /// Add extra rows in given dataset
        /// </summary>
        /// <param name="dsObj">dataset</param>
        /// <returns>dataset</returns>
        private DataSet AddFieldsInDataSet(DataSet dsObj)
        {
            //Add a new row.
            DataRow dr;
            dr = dsObj.Tables[0].NewRow();
            dr[1] = "0";
            dr[0] = Msg.GetMsg(Envs.GetContext(), "All", true);
            //dsObj.Tables[0].Rows.InsertAt(dr, 0);
            dsObj.Tables[0].Rows.Insert(0, dr);

            dr = dsObj.Tables[0].NewRow();
            dr[1] = "365";
            dr[0] = Msg.GetMsg(Envs.GetContext(), "YearAll", true);
            //dsObj.Tables[0].Rows.InsertAt(dr, 1);
            dsObj.Tables[0].Rows.Insert(1, dr);

            dr = dsObj.Tables[0].NewRow();
            dr[1] = "365|C";
            dr[0] = Msg.GetMsg(Envs.GetContext(), "YearCreated", true);
            //dsObj.Tables[0].Rows.InsertAt(dr, 2);
            dsObj.Tables[0].Rows.Insert(2, dr);

            dr = dsObj.Tables[0].NewRow();
            dr[1] = "31";
            dr[0] = Msg.GetMsg(Envs.GetContext(), "MonthAll", true);
            //dsObj.Tables[0].Rows.InsertAt(dr, 3);
            dsObj.Tables[0].Rows.Insert(3, dr);

            dr = dsObj.Tables[0].NewRow();
            dr[1] = "31|C";
            dr[0] = Msg.GetMsg(Envs.GetContext(), "MonthCreated", true);
            //dsObj.Tables[0].Rows.InsertAt(dr, 4);
            dsObj.Tables[0].Rows.Insert(4, dr);

            dr = dsObj.Tables[0].NewRow();
            dr[1] = "7";
            dr[0] = Msg.GetMsg(Envs.GetContext(), "WeekAll", true);
            //dsObj.Tables[0].Rows.InsertAt(dr, 5);
            dsObj.Tables[0].Rows.Insert(5, dr);

            dr = dsObj.Tables[0].NewRow();
            dr[1] = "7|C";
            dr[0] = Msg.GetMsg(Envs.GetContext(), "WeekCreated", true);
            //dsObj.Tables[0].Rows.InsertAt(dr, 6);
            dsObj.Tables[0].Rows.Insert(6, dr);

            dr = dsObj.Tables[0].NewRow();
            dr[1] = "1";
            dr[0] = Msg.GetMsg(Envs.GetContext(), "DayAll", true);
            //dsObj.Tables[0].Rows.InsertAt(dr, 7);
            dsObj.Tables[0].Rows.Insert(7, dr);

            dr = dsObj.Tables[0].NewRow();
            dr[1] = "1|C";
            dr[0] = Msg.GetMsg(Envs.GetContext(), "DayCreated", true);
            //dsObj.Tables[0].Rows.InsertAt(dr, 8);
            dsObj.Tables[0].Rows.Insert(8, dr);

            // return dataset
            return dsObj;
        }


        Image buttonImage = null;

        /// <summary>
        /// Set button enable or disable
        /// </summary>
        /// <param name="ibtn">button</param>
        /// <param name="isEnabled">bool type isenable</param>
        private void SetEnableButton(Button ibtn, bool isEnabled)//private void SetEnableButton(ImageButton ibtn, bool isEnabled)
        {
            if (ibtn == ibtnDelQuery)
            {

                ibtn.IsEnabled = isEnabled;
                //if (isEnabled)
                //{
                //    //ibtn.NormalImage = VAdvantage.Properties.Resources.delete;
                //    buttonImage = new Image();
                //    buttonImage.Source = Envs.LoadImageSource("delete.png");
                //    ibtn.Content  = buttonImage;
                //}
                //else
                //{
                //    //ibtn.NormalImage = VAdvantage.Properties.Resources.delete_high_volume_disable;
                //    buttonImage = new Image();
                //        buttonImage.Source = Envs.LoadImageSource("delete_high_volume_disable.png");
                //    ibtn.Content = buttonImage;
                //}
            }
            else if (ibtn == ibtnSaveRow)
            {
                ibtn.IsEnabled = isEnabled;
                //if (isEnabled)
                //{
                //    //ibtn.NormalImage = VAdvantage.Properties.Resources.save;
                //    buttonImage = new Image();
                //    buttonImage.Source = Envs.LoadImageSource("save.png");
                //    ibtn.Content = buttonImage;
                //}
                //else
                //{
                //    //   ibtn.NormalImage = VAdvantage.Properties.Resources.save_high_volume_disable;
                //    buttonImage = new Image();
                //    buttonImage.Source = Envs.LoadImageSource("save_high_volume_disable.png");
                //    ibtn.Content = buttonImage;
                //}
            }
            //buttonImage = null;
        }

        #endregion

        protected override void OnKeyDown(KeyEventArgs e)
        {
            //if (e.KeyCode == Keys.N && e.Modifiers == Keys.Alt && vtabLookup.SelectedIndex == 0)
            //{
            //    NewRecord();
            //}
            //else if (e.KeyCode == Keys.Q && e.Modifiers == Keys.Alt && vtabLookup.SelectedIndex == 1)
            //{
            //    Requery();
            //}
        }

        /*****************************************************/

        //  private void Find_Load(object sender, EventArgs e)
        private void ChildWindow_Loaded(object sender, RoutedEventArgs e)
        {
            //this.SelectNextControl(tblpnlS, true, false, true, true);//silverlight comment
            

            //FillList()for despature

            // set tooltip to all buttons
            // ToolTip ttp = new ToolTip();//comment for silverlight
            //ttp.Active = true;//comment for silverlight
            ToolTipService.SetToolTip(ibtnNewRec, Msg.GetMsg(Envs.GetContext(), "New", true) + " Alt+N");
            ToolTipService.SetToolTip(ibtnOKA, Msg.GetMsg(Envs.GetContext(), "QueryEnter", true));
            ToolTipService.SetToolTip(ibtnOKS, Msg.GetMsg(Envs.GetContext(), "QueryEnter", true));
            ToolTipService.SetToolTip(ibtnCancelA, Msg.GetMsg(Envs.GetContext(), "QueryCancel", true));
            ToolTipService.SetToolTip(ibtnCancelS, Msg.GetMsg(Envs.GetContext(), "QueryCancel", true));
            ToolTipService.SetToolTip(ibtnSaveRow, Msg.GetMsg(Envs.GetContext(), "QuerySaveRow", true));
            ToolTipService.SetToolTip(ibtnDelQuery, Msg.GetMsg(Envs.GetContext(), "QueryDelete", true));
            ToolTipService.SetToolTip(ibtnRequery, Msg.GetMsg(Envs.GetContext(), "Refresh", true) + " Alt+Q");
            ToolTipService.SetToolTip(vcmbQueryA, Msg.GetMsg(Envs.GetContext(), "QueryName", true));
            ToolTipService.SetToolTip(lstQuery, Msg.GetMsg(Envs.GetContext(), "DoubleClickQuery"));
            //ToolTipService.SetToolTip(pnlQuery, Msg.GetMsg(Env.GetContext(), "DoubleClickOnQueryForSearch"));//no panal used in silverlight
            // to remove "&" from tooltip text
            //ttp.StripAmpersands = true;
            // ttp.ShowAlways = true;

            //ibtnDeleteTab2.Source = Envs.LoadImageSource("cross16.png");
            //ibtnSaveTab2.Source = Envs.LoadImageSource("save.png");
        }

        private void FillList(DataSet dsListQueries)
        {
            //fill listbox
            //FillCombo.FillList(lstQuery, "Name", "Code", AddFieldsInDataSet(dsListQueries));//silverlight comment

            IList lst = AddFieldsInDataSet();

            if (dsListQueries.Tables[0].Rows.Count > 0)
            {
                //DataTable ds = AddFieldsInDataSet(dsListQueries).Tables[0];
                foreach (DataRow dr in dsListQueries.Tables[0].Rows)
                {
                    ValueNamePair knp = new ValueNamePair(dr[1].ToString(), dr[0].ToString());
                    lst.Add(knp);
                }
            }
            //else
            //{
            lstQuery.ItemsSource = lst;
                AddDoubleClick();
            //}


            // set tab properties

            //vtabLookup.DisplayManager = VTabControl.VTabControl.TabControlDisplayManager.Custom;//silverlight comment
            //CommonFunctions.SetTabProperties(vtabLookup);//silverlight comment
            // set text of tab according to language

            //silver light comment for run time text
            //vtabPAdvanced.Text = Msg.GetMsg(Env.GetContext(), "Advanced", true).Replace("&", "");
            //vtabPLookup.Text = Msg.GetMsg(Env.GetContext(), "Find", true).Replace("&", "");

            vlblRecent.Content = Msg.GetMsg(Envs.GetContext(), "VHistory", true);
        }

        private void AddDoubleClick()
        {
            //foreach (KeyValuePair<object, DependencyObject> an in lstQuery.GetItemsAndContainers())
            //{
            //    //helper = new SilverlightDesktop.Common.DoubleClickHelper(an);
            //    //helper.DoubleClick += new EventHandler<MouseButtonEventArgs>(helper_DoubleClick);
            //    //helper.Click += new EventHandler<MouseButtonEventArgs>(helper_Click);
            //}

            //foreach (ListBoxItem an in lstQuery.Items)
            //{
            //    helper = new SilverlightDesktop.Common.DoubleClickHelper(an);
            //    helper.DoubleClick += new EventHandler<MouseButtonEventArgs>(helper_DoubleClick);
            //    helper.Click += new EventHandler<MouseButtonEventArgs>(helper_Click);
            //}
        }

        private ObservableCollection<ValueNamePair> AddFieldsInDataSet()
        {
            ObservableCollection<ValueNamePair> list = new ObservableCollection<ValueNamePair>();
            list.Add(new ValueNamePair("0", Msg.GetMsg(Envs.GetContext(), "All", true)));
            list.Add(new ValueNamePair("365", Msg.GetMsg(Envs.GetContext(), "YearAll", true)));
            list.Add(new ValueNamePair("365 | C", Msg.GetMsg(Envs.GetContext(), "YearCreated", true)));
            list.Add(new ValueNamePair("31", Msg.GetMsg(Envs.GetContext(), "MonthAll", true)));
            list.Add(new ValueNamePair("31 | C", Msg.GetMsg(Envs.GetContext(), "MonthCreated", true)));
            list.Add(new ValueNamePair("7", Msg.GetMsg(Envs.GetContext(), "WeekAll", true)));
            list.Add(new ValueNamePair("7 | C", Msg.GetMsg(Envs.GetContext(), "WeekCreated", true)));
            list.Add(new ValueNamePair("1", Msg.GetMsg(Envs.GetContext(), "DayAll", true)));
            list.Add(new ValueNamePair("1 | C", Msg.GetMsg(Envs.GetContext(), "DayCreated", true)));
            return list;
        }
      
        private void ibtnNewRec_Click(object sender, RoutedEventArgs e)
        {
            NewRecord();
        }

        private void ibtnCancelA_Click(object sender, RoutedEventArgs e)
        {
            _isOkPressed = false;
            // set query to null and close this window
            _query = null;
            _total = 999999;
            Close(false);
        }

        private void ibtnOKA_Click(object sender, RoutedEventArgs e)
        {
            //for (int i = 0; i < tblpnlA2.Controls.Count; i++)
            
            for (int i = 0; i < tblpnlA.Children.Count; i++)
            {
                //if (tblpnlA2.Controls[i] is VTextBoxButton)
                if (tblpnlA.Children[i] is VTextBoxButton)
                {
                    //VTextBoxButton tb = (VTextBoxButton)tblpnlA2.Controls[i];
                    VTextBoxButton tb = (VTextBoxButton)tblpnlA.Children[i];
                    if (tb.Focused && tb.GetValue() == DBNull.Value)
                    {
                        tb.SetEnterKeyDown(true);
                        return;
                    }
                }
            }
            SetBusy(true);
            _isOkPressed = true;
            _isOkButtonPressed = true;
            //	Save pending
            SaveAdvanced();
            // if total records > 0, then close this window
            
        }

        private void ibtnRequery_Click(object sender, RoutedEventArgs e)
        {
            Requery();
        }

        private void ibtnSaveRow_Clcik(object sender, RoutedEventArgs e)
        {
            // save a row temporary into a dataset
            SaveRowTemp();
        }

        private void ibtnDelQuery_Click(object sender, RoutedEventArgs e)
        {
            object obj = vcmbQueryA.SelectedValue;
            if (obj == null || obj.ToString() == "")
                return;

            SetBusy(true);
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {

                MUserQuery uq;
                                   // deletes a selected query in combobox
                    uq = new MUserQuery(_ctx, int.Parse(obj.ToString()), null);
                if (uq == null)
                    return;
                // get name of the query
                string name = uq.GetName();
                // delete query
                if (uq.Delete(true))
                {
                    // if query deleted succesfully, remove the query name from combobox
                    //vcmbQueryA.Items.RemoveAt(vcmbQueryA.SelectedIndex);
                    //FillQuery();
                    DataSet dsQueries = MUserQuery.GetDataSet(_ctx, _AD_Tab_ID, _AD_Table_ID, "AD_UserQuery_ID");
                    System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => FillCombo(vcmbQueryA, "Name", "AD_UserQuery_ID", dsQueries));
                    System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => DeleteQuery(true, name, obj));

                    //vcmbQueryA.SelectedIndex = 0;
                    //// show message to user
                    ////ShowMessage.Info("Deleted", true, name, "");
                    //MessageBox.Show("Deleted" + name);
                    //vtxtQueryName.Text = "";
                    //vtxtQueryName.IsEnabled = false;
                }
                else
                {
                    System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => DeleteQuery(false, "", obj));
                    // MessageBox.Show("DeleteError");
                }
            });
        }
        private void DeleteQuery(bool msg, string name, object obj)
        {
            if (msg)
            {
                if (obj != null)
                    vcmbQueryA.SelectedIndex = 0;
                // show message to user
                ShowMessage.Info("Deleted", true, name, "");
                //MessageBox.Show("Deleted" + name);
                vtxtQueryName.Text = "";
                vtxtQueryName.IsEnabled = false;
            }
            else
            {
                ShowMessage.Info("DeleteError", true, name, "");
                //MessageBox.Show("DeleteError");
            }
            SetBusy(false);
        }


        private void vcmbColumn_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            chkDynamic.IsChecked = false;
            SetDynamicControlsVisible(false,false);
            // set control at value1 position according to the column selected
            string columnName = "";
            // set control at value2 position according to the operator selected
            if (vcmbColumn.SelectedValue == null)
            {
                columnName = "";
            }
            else
            {
                columnName = vcmbColumn.SelectedValue.ToString();
            }
            if (vcmbColumn.SelectedValue != null && columnName != "System.Data.DataRowView" && columnName != "0")
            {
                DataSet dsOp = null;
                DataSet dsOpDynamic = null;
                // if column name is of ant ID
                if (columnName.EndsWith("_ID") || columnName.EndsWith("_Acct"))
                {
                    // fill dataset with operators of type ID
                    dsOp = GetOperatorsQuery(Query.OPERATORS_ID);
                   

                }
                else if (columnName.StartsWith("Is"))
                {
                    // fill dataset with operators of type Yes No
                    dsOp = GetOperatorsQuery(Query.OPERATORS_YN);
                }
                else
                {
                    // fill dataset with all operators available
                    dsOp = GetOperatorsQuery(Query.OPERATORS);
                }




                //if (curTab != null)
                //{
                //    vcmbColumn.SelectedIndex = -1;
                //    return;
                //}

                GridField f = curTab.GetField(columnName);


                if (f!= null && DisplayType.IsDate(f.GetDisplayType()))
                {
                    dsOpDynamic = GetOperatorsQuery(Query.OPERATORS_DATE_DYNAMIC);
                    Common.FillCombo.Fill(cmbDymamicOp, "Name", "Value", dsOpDynamic);
                    SetDynamicControlsVisible(true,true);
                }
                else if(IsUserColumn(columnName))
                {
                     dsOpDynamic = GetOperatorsQuery(Query.OPERATORS_DYNAMIC_ID);
                    Common.FillCombo.Fill(cmbDymamicOp, "Name", "Value", dsOpDynamic);
                    SetDynamicControlsVisible(true,false);
                }

                // fill operator combobox

                Common.FillCombo.Fill(vcmbOperator, "Name", "Value", dsOp);
                vcmbOperator.SelectedIndex = 0;
                // get field
                GridField field = GetTargetMField(columnName);
                // set control at value1 position
                SetControl(true, field);
                // enable the save row button
                //ibtnSaveRow.Enabled = true;
                SetEnableButton(ibtnSaveRow, true);//silverlight comment
                vcmbOperator.IsEnabled = true;
            }
            // enable control at value1 position
            SetValueEnabled(true);
            // disable control at value2 position
            SetValue2Enabled(false);

        }

        private bool IsUserColumn(String columnName)
        {
            if (columnName.EndsWith("atedBy", StringComparison.OrdinalIgnoreCase) || columnName.Equals("AD_User_ID", StringComparison.OrdinalIgnoreCase))
                return true;
            if (columnName.Equals("SalesRep_ID", StringComparison.OrdinalIgnoreCase))
                return true;
            return false;
        }


        private void SetDynamicControlsVisible(bool visible,bool isDate)
        {
            chkDynamic.Visibility = visible ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            
            cmbDymamicOp.Visibility = visible ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            if (visible && isDate)
                cmbDymamicValue.Visibility = visible ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            else
            {
                cmbDymamicValue.Visibility = System.Windows.Visibility.Collapsed;
            }

            if (visible)
            {
                cmbDymamicOp.SelectionChanged += new SelectionChangedEventHandler(cmbDymamicOp_SelectionChanged);
                cmbDymamicOp.SelectedIndex = 0;
            }
            else
            {
                cmbDymamicOp.SelectionChanged -= new SelectionChangedEventHandler(cmbDymamicOp_SelectionChanged);
            } 
        }

        void cmbDymamicOp_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            cmbDymamicValue.SetDateStyle(cmbDymamicOp.SelectedIndex);
        }

        private void vcmbOperator_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string selOp = "";
            // set control at value2 position according to the operator selected
            if (vcmbOperator.SelectedValue == null)
            {
                selOp = "";
            }
            else
            {
                selOp = vcmbOperator.SelectedValue.ToString();
            }
            if (vcmbOperator.SelectedValue != null && selOp != "System.Data.DataRowView" && selOp != "0")
            {
                //if user selects between operator
                if (Query.BETWEEN.Equals(selOp))
                {
                    string columnName = vcmbColumn.SelectedValue.ToString();
                    // get field
                    GridField field = GetTargetMField(columnName);
                    // set control at value2 position
                    SetControl(false, field);
                    // enable the control at value2 position
                    SetValue2Enabled(true);
                }
            }
            else
            {
                //ibtnSaveRow.Enabled = false;
                SetEnableButton(ibtnSaveRow, false);//silverlight comment
                SetValue2Enabled(false);
            }
        }

        //private void vcmbQueryA_SelectedIndexChanged(object sender, EventArgs e)
        private void vcmbQueryA_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // binds grid according to the query selected in combobox
            if (vcmbQueryA.SelectedValue != null && vcmbQueryA.SelectedValue.ToString() != "0" && vcmbQueryA.SelectedValue.ToString() != "System.Data.DataRowView")
            {
                SetBusy(true);
                dsAdvanceData.Clear();
                 MUserQuery obj = null;
                 object value = vcmbQueryA.SelectedValue;

                System.Threading.ThreadPool.QueueUserWorkItem(delegate
                {
                    obj = new MUserQuery(_ctx, int.Parse(value.ToString()), null);
                    dsAdvanceData = obj.GetQueryLines();


                    System.Windows.Deployment.Current.Dispatcher.BeginInvoke(delegate
                    {
                        // bind grid with dataset
                        BindGrid(dsAdvanceData);
                        vtxtQueryName.Text =  ((System.Data.BindableObject)vcmbQueryA.SelectedItem).GetValue("NAME");//  .ToString();
                        vtxtQueryName.IsEnabled = true;
                        SetBusy(false);
                        SetEnableButton(ibtnDelQuery, true);//silverlight comment
                    });
                });
            }
            else
            {
                // if nothing is selected
                //ibtnDelQuery.Enabled = false;
                 SetEnableButton(ibtnDelQuery, false);//silverlight comment
                vtxtQueryName.Text = "";
                vtxtQueryName.IsEnabled = false;
                dsAdvanceData.Clear();
                BindGrid(null);
            }
        }

        //private void Find_FormClosing(object sender, FormClosingEventArgs e)
        private void ChildWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (!_isOkPressed)
            {
                // set query to null and close this window
                _query = null;
                _total = 999999;
            }
            // this.DialogResult = true;
        }

        // private void vtabLookup_SelectedIndexChanged(object sender, EventArgs e)
        private void vTabControl1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (vtabLookup != null)
            {
                IsFrameAccess = false;
                if (vtabLookup.SelectedIndex == (int)TabIndex.enmDefault)
                {
                    btnRemoveFrame.Visibility = System.Windows.Visibility.Collapsed;
                    lstQuery.Visibility = System.Windows.Visibility.Visible;
                    lstFrames.Visibility = System.Windows.Visibility.Collapsed;
                    btnAddNew.Visibility = System.Windows.Visibility.Collapsed;
                    lstKPI.Visibility = System.Windows.Visibility.Collapsed;
                    vlblRecent.Visibility = System.Windows.Visibility.Visible;
                    // this.AcceptButton = ibtnOKS;

                }
                else if (vtabLookup.SelectedIndex == (int)TabIndex.enmAdvanced)
                {
                    if (curTab == null)
                        vcmbColumn.IsEnabled = false;
                    else
                        vcmbColumn.IsEnabled = true;

                    btnRemoveFrame.Visibility = System.Windows.Visibility.Collapsed;
                    btnAddNew.Visibility = System.Windows.Visibility.Collapsed;
                    lstQuery.Visibility = System.Windows.Visibility.Visible;
                    lstFrames.Visibility = System.Windows.Visibility.Collapsed;
                    lstKPI.Visibility = System.Windows.Visibility.Collapsed;
                    InitFindAdvanced();
                    vlblRecent.Visibility = System.Windows.Visibility.Visible;
                    //this.AcceptButton = ibtnOKA;
                }
                else if (vtabLookup.SelectedIndex == (int)TabIndex.enmFrame)
                {
                    if (!isAlreadyLoaded)
                        LoadRoleCenterTab();

                    lstQuery.Visibility = System.Windows.Visibility.Collapsed;
                    lstFrames.Visibility = System.Windows.Visibility.Visible;
                    btnRemoveFrame.Visibility = System.Windows.Visibility.Visible;
                    btnAddNew.Visibility = System.Windows.Visibility.Visible;
                    lstKPI.Visibility = System.Windows.Visibility.Collapsed;
                    vlblRecent.Visibility = System.Windows.Visibility.Visible;
                }
                else if (vtabLookup.SelectedIndex == (int)TabIndex.enmKPI)
                {
                    if (!isAlreadyLoaded)
                        LoadRoleCenterTab();

                    lstKPI.Visibility = System.Windows.Visibility.Visible;
                    lstQuery.Visibility = System.Windows.Visibility.Collapsed;
                    lstFrames.Visibility = System.Windows.Visibility.Collapsed;
                    btnRemoveFrame.Visibility = System.Windows.Visibility.Visible;
                    btnAddNew.Visibility = System.Windows.Visibility.Visible;
                    vlblRecent.Visibility = System.Windows.Visibility.Visible;
                }
                else if (vtabLookup.SelectedIndex == (int)TabIndex.enmFrameAccess)
                {
                    vlblRecent.Visibility = System.Windows.Visibility.Collapsed;
                    IsFrameAccess = true;
                    cmbFrame.SelectedIndex = -1;

                    rdRole.IsChecked = true;
                    if (!isAlreadyLoaded)
                        LoadRoleCenterTab();

                    lstKPI.Visibility = System.Windows.Visibility.Collapsed;
                    lstQuery.Visibility = System.Windows.Visibility.Collapsed;
                    lstFrames.Visibility = System.Windows.Visibility.Collapsed;
                    btnRemoveFrame.Visibility = System.Windows.Visibility.Collapsed;
                    btnAddNew.Visibility = System.Windows.Visibility.Collapsed;

                    vgridAcess.DataContext = null;
                    vgridAcess.ItemsSource = null;
                    //vdgvQuery.DataBindings.Clear();
                    vgridAcess.Columns.Clear();

                }
                else
                {
                    vlblRecent.Visibility = System.Windows.Visibility.Collapsed;
                    cmbKPI.SelectedIndex = -1;

                    rdRole1.IsChecked = true;
                    if (!isAlreadyLoaded)
                        LoadRoleCenterTab();

                    lstKPI.Visibility = System.Windows.Visibility.Collapsed;
                    lstQuery.Visibility = System.Windows.Visibility.Collapsed;
                    lstFrames.Visibility = System.Windows.Visibility.Collapsed;
                    btnRemoveFrame.Visibility = System.Windows.Visibility.Collapsed;
                    btnAddNew.Visibility = System.Windows.Visibility.Collapsed;

                    vgridKPIAcess.DataContext = null;
                    vgridKPIAcess.ItemsSource = null;
                    //vdgvQuery.DataBindings.Clear();
                    vgridKPIAcess.Columns.Clear();
                }
            }

        }

        //private void lstQuery_MouseDoubleClick(object sender, MouseEventArgs e)
        //{
        //    //
        //    object xx = lstQuery.SelectedItem;
        //    if (xx != null)
        //    {
        //        string val = lstQuery.SelectedValue.ToString();
        //        if (lstQuery.SelectedIndex < 9)
        //        {
        //            string[] valSplit = val.Split('|');
        //            int cnt = valSplit.Length;
        //            if (cnt == 1)
        //            {
        //                _created = false;
        //            }
        //            else
        //            {
        //                _created = true;
        //            }

        //            _days = int.Parse(valSplit[0]);
        //            val = "";
        //        }
        //        else
        //        {
        //            _days = 0;
        //        }

        //        _query = new Query(_tableName);
        //        _query.AddRestriction(val);
        //        int no = GetNoOfRecords(_query, true);
        //        _query.SetRecordCount(no);
        //        if (no != 0)
        //        {
        //            _isOkButtonPressed = true;
        //            this.Close();
        //        }
        //    }
        //    else
        //    {
        //        _isOkButtonPressed = false;
        //        _isOkPressed = false;
        //        this.Close();
        //    }

        //}

        //listview
        //private void lstQuery_Loaded(object sender, RoutedEventArgs e)
        //{
        //    //ObservableCollection<string> list = new ObservableCollection<string>();
        //    //for (int i = 0; i < 10; i++)
        //    //    list.Add("Item " + i.ToString());
        //    //lstQuery.ItemsSource = list;
        //}

        //void timer_Tick(object sender, EventArgs e)
        //{
        //    timer.Stop();
        //    singleClick = false; // expires
        //}

        //private void Grid_Loaded(object sender, RoutedEventArgs e)
        //{
        //    //FrameworkElement g = sender as FrameworkElement;
        //    //g.Width = lstQuery.ActualWidth;
        //}

        //private void Grid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        //{
        //    if (!singleClick)
        //    {
        //        timer.Start();
        //        singleClick = true;
        //    }
        //    else
        //    {


        //    }
        //}
        private void lstQuery_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //singleClick = false;
            //DependencyObject deo = null;
            //ListBoxItem item = lstQuery.SelectedItem as ListBoxItem;
            //IEnumerable<KeyValuePair<object, DependencyObject>> en = lstQuery.GetItemsAndContainers();
            //foreach (KeyValuePair<object, DependencyObject> obj in en)
            //{
            //    if (obj.Key.Equals(lstQuery.SelectedItem))
            //    {
            //        deo = obj.Value;
            //        break;
            //    }
            //}
            //if (deo == null)
            //{
            //    return;
            //}

            //if (helper != null)
            //{
            //    helper.DoubleClick -= new EventHandler<MouseButtonEventArgs>(helper_DoubleClick);
            //    helper.Dispose();
            //}
            //((FrameworkElement)deo).MouseLeftButtonDown += new MouseButtonEventHandler(Find_MouseLeftButtonDown);
            // helper = new SilverlightDesktop.Common.DoubleClickHelper((FrameworkElement)deo);
            //helper.DoubleClick+=new EventHandler<MouseButtonEventArgs>(helper_DoubleClick);

        }

        void Find_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            //MessageBox.Show("haha");
        }


        private void SetBusy(bool isBusy)
        {
            this.vtabLookup.IsEnabled = !isBusy;
            this.Cursor = isBusy ? Cursors.Wait : Cursors.Arrow;
            this.HasCloseButton = !isBusy;
            lstQuery.IsEnabled = !isBusy;
        }


        private void ibtnOKS_Click(object sender, RoutedEventArgs e)
        {

            SetBusy(true);

            //for (int i = 0; i < tblpnlS.Controls.Count; i++)
            for (int i = 0; i < tblpnlS.Children.Count; i++)
            {
                //if (tblpnlS.Controls[i] is VTextBoxButton)
                if (tblpnlS.Children[i] is VTextBoxButton)
                {
                    VTextBoxButton tb = (VTextBoxButton)tblpnlS.Children[i];
                    if (tb.Focused && tb.GetValue() == DBNull.Value)
                    {
                        tb.SetEnterKeyDown(true);
                        SetBusy(false);
                        return;
                    }
                }
            }

            _isOkPressed = true;
            _isOkButtonPressed = true;
            //	Create Query String
            _query = new Query(_tableName);
            // check if user has entered any text in name
            string value = "";
            if ((_hasName) && !vtxtName.Text.Trim().Equals("%") && vtxtName.Text.Trim().Length != 0)
            {
                value = vtxtName.Text.Trim().ToUpper();
                if (!value.EndsWith("%"))
                {
                    value += "%";
                }
                // add to the query
                _query.AddRestriction("Name", Query.LIKE, value, vlblName.Content.ToString(), value);
            }
            // check if user has entered any text in description
            if (_hasDescription && !vtxtDesc.Text.Trim().Equals("%") && vtxtDesc.Text.Trim().Length != 0)
            {
                value = vtxtDesc.Text.Trim().ToUpper();
                if (!value.EndsWith("%"))
                {
                    value += "%";
                }
                // add to the query
                _query.AddRestriction("Description", Query.LIKE, value, vlblDesc.Content.ToString(), value);
            }
            // check if user has entered any text in SearchKey
            if (_hasSearchKey && !vtxtSearchKey.Text.Trim().Equals("%") && vtxtSearchKey.Text.Trim().Length != 0)
            {
                value = vtxtSearchKey.Text.Trim().ToUpper();
                if (!value.EndsWith("%"))
                {
                    value += "%";
                }
                // add to the query
                _query.AddRestriction("Value", Query.LIKE, value, vlblSearchKey.Content.ToString(), value);
            }
            // check if user has entered any text in DocumentNo
            if (_hasDocNo && !vtxtDocNo.Text.Trim().Equals("%") && vtxtDocNo.Text.Trim().Length != 0)
            {
                value = vtxtDocNo.Text.Trim().ToUpper();
                if (!value.EndsWith("%"))
                {
                    value += "%";
                }
                // add to the query
                _query.AddRestriction("DocumentNo", Query.LIKE, value, vlblDocNo.Content.ToString(), value);
            }
            //	Special Controls
            int editorCount = _sEditors.Count;
            for (int i = 0; i < editorCount; i++)
            {
                // get extra controls one by one
                IControl ved = (IControl)_sEditors[i];
                // get value of the control
                object val = ved.GetValue();
                // if any value exists
                if (val != null && val.ToString().Trim().Length > 0 && val.ToString().ToUpper() != "NULL")
                {
                    // get column name of the field
                    string columnName = ved.GetName();
                    string sqlQuery = columnName;
                    GridField field = ved.GetField();
                    if (field != null)
                    {
                        //string sql = field.GetColumnSQL(false);	//	virtual column
                        string sql = field.GetColumnSQL();
                        if (sql != null && sql.Length > 0)
                            sqlQuery = sql;
                    }
                    if (ved.GetDisplayType() == DisplayType.YesNo)
                    {
                        // if checkbox is selected
                        if (val.ToString().ToLower() == "true")
                        {
                            val = "Y";
                        }
                        else
                        {
                            val = "N";
                        }
                    }
                    // add to query
                    if (val.ToString().IndexOf("%") != -1)
                        _query.AddRestriction(sqlQuery, Query.LIKE, val, columnName, ved.GetText());
                    else
                        _query.AddRestriction(sqlQuery, Query.EQUAL, val, columnName, ved.GetText());
                }
            }

            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                //	Test for no records
                if (GetNoOfRecords(_query, true) != 0)
                {
                    System.Windows.Deployment.Current.Dispatcher.BeginInvoke(closeMyWindow);
                }
                else
                {
                    System.Windows.Deployment.Current.Dispatcher.BeginInvoke(()=>SetBusy(false));
                }
            });
        }
        private void closeMyWindow()
        {
            Close(true);
        }

        private void ibtnCancelS_Click(object sender,RoutedEventArgs e)
        {
            _isOkPressed = false;
            // set query to null and close this window
            _query = null;
            _total = 999999;
            Close(false);
        }

        private void vdgvQuery_Unloaded(object sender, RoutedEventArgs e)
        {

        }

        private void Grid_Loaded(object sender, RoutedEventArgs e)
        {
            
            helper = new SilverlightDesktop.Common.DoubleClickHelper((FrameworkElement)sender);
            helper.DoubleClick += new EventHandler<MouseButtonEventArgs>(helper_DoubleClick);
           // helper.Click += new EventHandler<MouseButtonEventArgs>(helper_Click);
        }


        #region Role Center
        void LoadFrames()
        {
            String RoleQuery = " AD_Role_ID = " + Envs.GetCtx().GetAD_Role_ID() + " And AD_User_ID = " + Envs.GetCtx().GetAD_User_ID();
            string sql = "Select RC_View_ID, Name from RC_View WHERE " + RoleQuery + "  AND IsActive = 'Y' AND AD_Tab_ID =" + _AD_Tab_ID + " And AD_Table_ID = " + _AD_Table_ID;
            sql = MRole.GetDefault().AddAccessSQL(sql, "RC_View", false, false);
            IDataReader drFrames = DB.ExecuteReader(sql);
            while (drFrames.Read())
            {
                KeyNamePair frameskeys = new KeyNamePair(int.Parse(drFrames[0].ToString()), drFrames[1].ToString());
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => lstFrames.Items.Add(frameskeys));
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => cmbFrame.Items.Add(frameskeys));
            }
            drFrames.Close();

            sql = "Select RC_KPI_ID, Name from RC_KPI WHERE " + RoleQuery + " AND IsActive = 'Y' AND AD_Tab_ID =" + _AD_Tab_ID + " And AD_Table_ID = " + _AD_Table_ID;
            sql = MRole.GetDefault().AddAccessSQL(sql, "RC_KPI", false, false);
            IDataReader drKPI = DB.ExecuteReader(sql);
            while (drKPI.Read())
            {
                KeyNamePair frameskeys = new KeyNamePair(int.Parse(drKPI[0].ToString()), drKPI[1].ToString());
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => lstKPI.Items.Add(frameskeys));
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => cmbKPI.Items.Add(frameskeys));
            }
            drFrames.Close();
        }

        bool isAlreadyLoaded = false;
        //bool isAlreadyLoadedKPITab = false;
        List<KeyNamePair> colors = new List<KeyNamePair>();
        List<KeyNamePair> KPICols = new List<KeyNamePair>();
        List<KeyNamePair> AvailCols = new List<KeyNamePair>();

        void LoadRoleCenterTab()
        {
            SetFrameBusy(true);
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {

                LoadFrames();
                DataSet dsQueries = MUserQuery.GetDataSet(_ctx, _AD_Tab_ID, _AD_Table_ID, "AD_UserQuery_ID");
                //System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => FillCombo(cmbSavedQuery, "Name", "AD_UserQuery_ID", dsQueries));

                for (int i = 0; i <= dsQueries.Tables[0].Rows.Count - 1; i++)
                {
                    string key = dsQueries.Tables[0].Rows[i]["AD_UserQuery_ID"].ToString();
                    string value = dsQueries.Tables[0].Rows[i]["Name"].ToString();
                    KeyNamePair queries = new KeyNamePair(int.Parse(key), value);
                    System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => cmbSavedQuery.Items.Add(queries));
                    System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => cmbKPISearch.Items.Add(queries));
                    ListQueries.Add(queries);
                }


                string sql = "Select AD_Field_ID, Name from AD_Field where IsActive = 'Y' AND AD_Tab_ID =" + _AD_Tab_ID;
                IDataReader dr = null;

                for (int c = 0; c < _findFields.Length; c++)
                {
                    // get field
                    GridField field = _findFields[c];

                    if (!field.IsDisplayed())
                        continue;

                    if (field.IsEncrypted())
                        continue;
                    // get field's column name
                    string columnName = field.GetColumnName();
                    if (field.GetDisplayType() == DisplayType.Button)
                    {
                        if (field.GetAD_Reference_Value_ID() == 0)
                            continue;
                        if (columnName.EndsWith("_ID"))
                            field.SetDisplayType(DisplayType.Table);
                        else
                            field.SetDisplayType(DisplayType.List);
                        field.LoadLookUp();
                    }
                    // get text to be displayed
                    string header = field.GetHeader();
                    if (header == null || header.Length == 0)
                    {
                        // get text according to the language selected
                        header = Msg.GetElement(_ctx, columnName);
                        if (header == null || header.Length == 0)
                            continue;
                    }
                    // if given field is any key, then add "(ID)" to it
                    if (field.IsKey())
                        header += (" (ID)");

                    if (field.GetDisplayType() == DisplayType.YesNo)
                    {
                        //KeyNamePair yesno = new KeyNamePair(field.GetAD_Field_ID(), header);
                        //System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => cmbActionCols.Items.Add(yesno));

                    }
                    else
                    {
                        KeyNamePair keys = new KeyNamePair(field.GetAD_Field_ID(), header);
                        AvailCols.Add(keys);
                        System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => lstAvailabelCols.Items.Add(keys));

                        if (field.GetDisplayType() == DisplayType.Integer || field.GetDisplayType() == DisplayType.Number || field.GetDisplayType() == DisplayType.Amount
                             ||  DisplayType.CostPrice == field.GetDisplayType() || DisplayType.Quantity == field.GetDisplayType())
                        {
                            KeyNamePair onlyCols = new KeyNamePair(field.GetAD_Column_ID(), header);
                            KPICols.Add(onlyCols);
                            System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => cmbKPICol.Items.Add(onlyCols));
                        }
                    }
                }

                
                
                sql = "Select AD_PrintColor_ID, Name from AD_PrintColor WHERE IsActive = 'Y'";
                dr = DB.ExecuteReader(sql, null);

                while (dr.Read())
                {
                    KeyNamePair keys = new KeyNamePair(int.Parse(dr[0].ToString()), dr[1].ToString());
                    colors.Add(keys);
                    System.Windows.Deployment.Current.Dispatcher.BeginInvoke(delegate
                    {

                        cmbBGColor.Items.Add(keys);
                    });
                    System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => cmbHeaderBGColor.Items.Add(keys));
                    //System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => cmbHeaderFontColor.Items.Add(keys));
                    //System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => cmbFontColor.Items.Add(keys));
                }
                dr.Close();

                //sql = "Select AD_Image_ID, Name from AD_Image";
                //dr = DB.ExecuteReader(sql, null);

                //while (dr.Read())
                //{
                //    KeyNamePair keys = new KeyNamePair(int.Parse(dr[0].ToString()), dr[1].ToString());
                //    System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => cmbImage.Items.Add(keys));
                //}
                //dr.Close();


                //DataTable dt = new DataTable("SQLOP");
                //DataColumn dcol;
                //DataRow drow;
                //dcol = new DataColumn("Name");
                //dt.Columns.Add(dcol);
                //dcol = new DataColumn("Value");
                //dt.Columns.Add(dcol);

                //drow = dt.NewRow();
                //drow[0] = " "; // Name
                //drow[1] = ""; // DB
                //dt.Rows.Add(drow);

                //drow = dt.NewRow();
                //drow[0] = "Update"; // Name
                //drow[1] = "U"; // DB
                //dt.Rows.Add(drow);

                //drow = dt.NewRow();
                //drow[0] = "Delete"; // Name
                //drow[1] = "D"; // DB
                //dt.Rows.Add(drow);

                //DataSet ds = new DataSet();
                //ds.Tables.Add(dt);
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(delegate { SetFrameBusy(false); });

                isAlreadyLoaded = true;
                //isAlreadyLoadedKPITab = true;

            });            
        }

        #endregion

        private void TabItem_Loaded(object sender, RoutedEventArgs e)
        {
            
        }

        private void btnMoveRight_Click(object sender, RoutedEventArgs e)
        {
            if (lstAvailabelCols.SelectedIndex < 0)
                return;
            KeyNamePair selected = (lstAvailabelCols.SelectedItem as KeyNamePair);
            fieldList.Add(selected);
            lstSelectedCols.Items.Add(selected);
            lstAvailabelCols.Items.RemoveAt(lstAvailabelCols.SelectedIndex);
        }

        private void btnMoveLeft_Click(object sender, RoutedEventArgs e)
        {
            if (lstSelectedCols.SelectedIndex < 0)
                return;

            KeyNamePair selected = (lstSelectedCols.SelectedItem as KeyNamePair);

            if (selected.GetName().EndsWith("(Action)"))
            {
                lstSelectedCols.Items.RemoveAt(lstSelectedCols.SelectedIndex);

                int index = aName.IndexOf(selected.GetName().Replace(" (Action)", ""));
                aName.RemoveAt(index);
                aSQLOp.RemoveAt(index);
                aFieldID.RemoveAt(index);
                aImageID.RemoveAt(index);
                aValue.RemoveAt(index);
                fieldList.Remove(selected);
            }
            else
            {
                fieldList.Remove(selected);
                lstAvailabelCols.Items.Add(selected);
                lstSelectedCols.Items.RemoveAt(lstSelectedCols.SelectedIndex);
            }

        }

        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            //if (aName.Contains(txtActionName.Text))
            //    ShowMessage.Error(Msg.Translate(Envs.GetCtx(), "ActionAlreadyExists"), false);
            //else
            //{
            //    if(string.IsNullOrEmpty(txtActionName.Text))
            //        ShowMessage.Error(Msg.Translate(Envs.GetCtx(), "NameIsMandatory"), false);
            //    else if(cmbSQLOperation.SelectedIndex < 0)
            //        ShowMessage.Error(Msg.Translate(Envs.GetCtx(), "SQLOperationIsMandatory"), false);
            //    else if(cmbActionCols.SelectedIndex < 0)
            //        ShowMessage.Error(Msg.Translate(Envs.GetCtx(), "ActionFieldIsMandatory"), false);
            //    else if (cmbImage.SelectedIndex < 0)
            //        ShowMessage.Error(Msg.Translate(Envs.GetCtx(), "ActionImageIsMandatory"), false);
            //    else if (String.IsNullOrEmpty(txtActionValue.Text))
            //        ShowMessage.Error(Msg.Translate(Envs.GetCtx(), "ActionValueIsMandatory"), false);
            //    else
            //    {
                    
            //        aName.Add(txtActionName.Text);
            //        aSQLOp.Add((string)cmbSQLOperation.SelectedValue);
            //        aFieldID.Add(actionFieldID);
            //        aImageID.Add(actionImageID);
            //        aValue.Add(txtActionValue.Text);

            //        KeyNamePair actionCol = (KeyNamePair)cmbActionCols.SelectedItem;
            //        KeyNamePair newName = new KeyNamePair(actionCol.GetKey(), txtActionName.Text + " (Action)");
            //        fieldList.Add(newName);
            //        lstSelectedCols.Items.Add(newName);

                    //lstAction.Items.Add(txtActionName.Text + " : " + (string)cmbSQLOperation.SelectedItem + " ON " + actionCol.GetName());

                    //txtActionName.Text = "";
                    //cmbSQLOperation.SelectedIndex = -1;
                    //cmbImage.SelectedIndex = -1;
                    //txtActionValue.Text = "";
                    //cmbActionCols.SelectedIndex = -1;
            //    }
            //}
        }

        //All the fields
        List<KeyNamePair> fieldList = new List<KeyNamePair>();
        
        //Add action in lists
        List<String> aName = new List<string>();
        List<String> aSQLOp = new List<string>();
        List<int> aFieldID = new List<int>();
        List<int> aImageID = new List<int>();
        List<String> aValue = new List<string>();

        string name = "";
        string title = "";
        string desc = "";
        int search_id = 0;
        int minVal = 0;
        int maxVal = 0;

        int bgcolorid = 0;
        int fontcolorid = 0;
        int headerfontcolorid = 0;
        int headerbgcolorid = 0;



        private void btnSaveFrame_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {

        }

        

        private void btnSaveFrame_ImageFailed(object sender, ExceptionRoutedEventArgs e)
        {

        }

        private void cmbSavedQuery_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //if(cmbSavedQuery.SelectedIndex >= 0)
            //    search_id = int.Parse(cmbSavedQuery.SelectedValue.ToString());
        }

        private void cmbBGColor_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            KeyNamePair key = (KeyNamePair)cmbBGColor.SelectedItem;
            if (key == null)
                bgcolorid = 0;
            else
                bgcolorid = key.GetKey();
        }

        //private void cmbFontColor_SelectionChanged(object sender, SelectionChangedEventArgs e)
        //{
        //    KeyNamePair key = (KeyNamePair)cmbFontColor.SelectedItem;
        //    if (key == null)
        //        fontcolorid = 0;
        //    else
        //        fontcolorid = key.GetKey();
        //}

        //private void cmbHeaderFontColor_SelectionChanged(object sender, SelectionChangedEventArgs e)
        //{
        //    KeyNamePair key = (KeyNamePair)cmbHeaderFontColor.SelectedItem;
        //    if (key == null)
        //        headerfontcolorid = 0;
        //    else
        //        headerfontcolorid = key.GetKey();
        //}

        private void cmbHeaderBGColor_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            KeyNamePair key = (KeyNamePair)cmbHeaderBGColor.SelectedItem;
            if (key == null)
                headerbgcolorid = 0;
            else
                headerbgcolorid = key.GetKey();
        }

        int actionFieldID = 0;
        private void cmbActionCols_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //KeyNamePair key = (KeyNamePair)cmbActionCols.SelectedItem;
            //if (key == null)
            //    actionFieldID = 0;
            //else
            //    actionFieldID = key.GetKey();
        }

        int actionImageID = 0;
        private void cmbImage_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //KeyNamePair key = (KeyNamePair)cmbImage.SelectedItem;
            //if (key == null)
            //    actionImageID = 0;
            //else
            //    actionImageID = key.GetKey();
        }

        private void btnRemoveFrame_Click(object sender, RoutedEventArgs e)
        {
            if (vtabLookup.SelectedIndex == (int)TabIndex.enmKPI)
            {
                if (lstKPI.SelectedIndex < 0)
                    return;

                SetFrameBusy(true);
                KeyNamePair keys = (KeyNamePair)lstKPI.SelectedItem;
                BackgroundWorker bgw = new BackgroundWorker();
                bool b = false;
                bgw.DoWork += (sd, ed) =>
                {
                    X_RC_KPI view = new X_RC_KPI(Envs.GetCtx(), keys.GetKey(), null);
                    b = view.Delete(true);
                };

                bgw.RunWorkerCompleted += (sd, ed) =>
                {
                    if (b)
                    {
                        ShowMessage.Error(Msg.GetMsg("Deleted"), false);
                        cmbKPI.Items.RemoveAt(lstKPI.SelectedIndex);
                        lstKPI.Items.RemoveAt(lstKPI.SelectedIndex);
                        SetFrameBusy(false);
                        ClearAll();
                    }
                    else
                    {
                        SetFrameBusy(false);
                        ShowMessage.Error(Msg.GetMsg("DeleteError"), false);

                    }

                };

                bgw.RunWorkerAsync();
            }
            else
            {
                if (lstFrames.SelectedIndex < 0)
                    return;

                SetFrameBusy(true);
                KeyNamePair keys = (KeyNamePair)lstFrames.SelectedItem;

                BackgroundWorker bgw = new BackgroundWorker();
                bool b = false;
                bgw.DoWork += (sd, ed) =>
                {
                    X_RC_View view = new X_RC_View(Envs.GetCtx(), keys.GetKey(), null);
                    b = view.Delete(true);
                };

                bgw.RunWorkerCompleted += (sd, ed) =>
                {
                    if (b)
                    {
                        ShowMessage.Error(Msg.GetMsg("Deleted"), false);
                        cmbFrame.Items.RemoveAt(lstFrames.SelectedIndex);
                        lstFrames.Items.RemoveAt(lstFrames.SelectedIndex);
                        SetFrameBusy(false);
                        ClearAll();
                    }
                    else
                    {
                        SetFrameBusy(false);
                        ShowMessage.Error(Msg.GetMsg("DeleteError"), false);

                    }

                };

                bgw.RunWorkerAsync();
            }

        }

        private void SetFrameBusy(bool isBusy)
        {
            this.vtabLookup.IsEnabled = !isBusy;
            this.Cursor = isBusy ? Cursors.Wait : Cursors.Arrow;
            this.HasCloseButton = !isBusy;
            lstFrames.IsEnabled = !isBusy;
        }

        int iSelectedFrame = 0;

        private void lstFrames_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            
            if (lstFrames.SelectedIndex < 0)
                return;

            SetFrameBusy(true);
            KeyNamePair selected = (KeyNamePair)lstFrames.SelectedItem;
            iSelectedFrame = selected.GetKey();
            lstSelectedCols.Items.Clear();
            lstAvailabelCols.Items.Clear();

            List<KeyNamePair> AvailColsTemp = new List<KeyNamePair>();
            for (int c = 0; c <= AvailCols.Count - 1; c++)
            {
                lstAvailabelCols.Items.Add(AvailCols[c]);
                AvailColsTemp.Add(AvailCols[c]);
            }

            cmbBGColor.SelectedIndex = -1;
            //cmbHeaderFontColor.SelectedIndex = -1;
            cmbHeaderBGColor.SelectedIndex = -1;
            //cmbFontColor.SelectedIndex = -1;
            cmbSavedQuery.SelectedIndex = -1;

            fieldList.Clear();

            ThreadPool.QueueUserWorkItem(delegate
            {
                X_RC_View view = new X_RC_View(Envs.GetCtx(), selected.GetKey(), null);
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => txtName.Text = view.GetName() ?? "");
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => txtTitle.Text = view.GetTitle() ?? "");
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => txtDescription.Text = view.GetDescription() ?? "");
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => txtMaxValue.Text = view.GetMaxValue().ToString());
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => txtMinValue.Text = view.GetMinValue().ToString());

                string sql = "Select AD_Field_ID from RC_ViewColumn where IsActive = 'Y' AND RC_View_ID = " + view.Get_ID();
                IDataReader dr = DB.ExecuteReader(sql);
                if (dr != null)
                {
                    while (dr.Read())
                    {
                        MField saveFields = new MField(Envs.GetCtx(), int.Parse(dr["AD_Field_ID"].ToString()), null);
                        KeyNamePair keys = new KeyNamePair(saveFields.Get_ID(), saveFields.GetName());
                        fieldList.Add(keys);

                        bool pass = false;
                        System.Windows.Deployment.Current.Dispatcher.BeginInvoke(delegate
                        {
                            int index = AvailColsTemp.IndexOf(keys);
                            lstAvailabelCols.Items.RemoveAt(index);
                            AvailColsTemp.RemoveAt(index);

                            pass = true;
                        });

                        while (!pass)
                            Thread.Sleep(1);

                        pass = false;

                        System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => lstSelectedCols.Items.Add(keys));
                    }
                    dr.Close();
                }

                int index1 = -1;
                int index2 = -1;
                int index3 = -1;
                int index4 = -1;
                int savedValue = -1;
                for (int i = 0; i <= colors.Count - 1; i++)
                {
                    KeyNamePair current = colors[i];
                    if (current.GetKey() == view.GetBG_Color_ID())
                        index1 = i;
                    else if (current.GetKey() == view.GetFont_Color_ID())
                        index2 = i;
                    else if (current.GetKey() == view.GetHeaderBG_Color_ID())
                        index3 = i;
                    else if (current.GetKey() == view.GetHeaderFont_Color_ID())
                        index4 = i;

                }

                for (int i = 0; i <= ListQueries.Count - 1; i++)
                {
                    KeyNamePair current = ListQueries[i];
                    if (current.GetKey() == view.GetAD_UserQuery_ID())
                        savedValue = i;
                }

                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(delegate
                {
                    cmbBGColor.SelectedIndex = index1;
                    //cmbFontColor.SelectedIndex = index2;
                    cmbHeaderBGColor.SelectedIndex = index3;
                    //cmbHeaderFontColor.SelectedIndex = index4;
                    cmbSavedQuery.SelectedIndex = savedValue;
                });

                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => SetFrameBusy(false));
                

             });
            

        }

        private void Image_ImageFailed(object sender, ExceptionRoutedEventArgs e)
        {

        }

        void ClearAll()
        {
            if (vtabLookup.SelectedIndex == (int)TabIndex.enmKPI)
            {
                txtKPIDesc.Text = "";
                txtKPIName.Text = "";
                txtSearchKey.Text = "";
                cmbKPICol.SelectedIndex = -1;
                cmbKPISearch.SelectedIndex = -1;
                isSelectedKPI = 0;
                lstKPI.SelectedIndex = -1;
                rdSum.IsChecked = false;
                rdCount.IsChecked = false;
                rdMinimum.IsChecked = false;
                rdMaximum.IsChecked = false;
            }
            else
            {
                iSelectedFrame = 0;
                txtName.Text = "";
                txtTitle.Text = "";
                txtDescription.Text = "";
                txtMinValue.Text = "";
                txtMaxValue.Text = "";
                cmbBGColor.SelectedIndex = -1;
                cmbHeaderBGColor.SelectedIndex = -1;
                //cmbFontColor.SelectedIndex = -1;
                //cmbHeaderFontColor.SelectedIndex = -1;
                lstSelectedCols.Items.Clear();
                cmbSavedQuery.SelectedIndex = -1;
                lstFrames.SelectedIndex = -1;

                lstAvailabelCols.Items.Clear();
                for (int c = 0; c <= AvailCols.Count - 1; c++)
                {
                    lstAvailabelCols.Items.Add(AvailCols[c]);
                }
            }
        }

        private void btnAddNew_Click(object sender, RoutedEventArgs e)
        {
                ClearAll();

        }

        private void Image_ImageFailed_1(object sender, ExceptionRoutedEventArgs e)
        {

        }

        private void btnSaveFrame_Click(object sender, RoutedEventArgs e)
        {
            name = txtName.Text;
            title = txtTitle.Text;
            desc = txtDescription.Text;
            minVal =  Util.GetValueOfInt(txtMinValue.Text);
            maxVal = Util.GetValueOfInt(txtMaxValue.Text);
            int irv_view_id = 0;
            //Thread.Sleep(100);  //wait for values to be filled

            if (String.IsNullOrEmpty(name))
            {
                ShowMessage.Error(Msg.GetMsg("NameIsMandatory"), false);
                return;
            }
            else if (String.IsNullOrEmpty(title))
            {
                ShowMessage.Error(Msg.GetMsg("TitleIsMandatory"), false);
                return;
            }
            else if (lstSelectedCols.Items.Count <= 0)
            {
                ShowMessage.Error("SelectAtleastOneColumn", false);
                return;
            }
            else if (String.IsNullOrEmpty(minVal.ToString()))
            {
                ShowMessage.Error(Msg.GetMsg("MinValueIsMandatory"), false);
                return;
            }
            else if (String.IsNullOrEmpty(maxVal.ToString()))
            {
                ShowMessage.Error(Msg.GetMsg("MaxValueIsMandatory"), false);
                return;
            }


            KeyNamePair searchkey = cmbSavedQuery.SelectedItem as KeyNamePair;
            search_id = searchkey.GetKey();

            SetFrameBusy(true);
            BackgroundWorker bgw = new BackgroundWorker();
            bool b = false;
            bgw.DoWork += (sd, ed) =>
            {

                X_RC_View rc = new X_RC_View(Envs.GetContext(), iSelectedFrame, null);


                //rc.SetRC_View_ID(irv_view_id);
                rc.SetName(name);
                rc.SetTitle(title);
                rc.SetDescription(desc);
                rc.SetAD_UserQuery_ID(search_id);
                rc.SetMinValue(minVal);
                rc.SetMaxValue(maxVal);
                rc.SetBG_Color_ID(bgcolorid);
                //rc.SetFont_Color_ID(fontcolorid);
                //rc.SetHeaderFont_Color_ID(headerfontcolorid);
                rc.SetHeaderBG_Color_ID(headerbgcolorid);
                rc.SetAD_Tab_ID(_AD_Tab_ID);
                rc.SetAD_Table_ID(_AD_Table_ID);
                rc.SetAD_User_ID(Envs.GetCtx().GetAD_User_ID());
                rc.SetAD_Role_ID(Envs.GetCtx().GetAD_Role_ID());

                if (curTab.IsDetail())
                {
                    string lc = curTab.GetLinkColumnName();
                    if (!string.IsNullOrEmpty(lc))
                    {
                        string value = Envs.GetCtx().GetContext(curTab.GetWindowNo(), lc);
                        rc.SetRecord_ID(int.Parse(value));
                    }
                }

                b = rc.Save();
                irv_view_id = rc.Get_ID();

                if (b)  //only if saved
                {
                    X_RC_ViewAccess access = new X_RC_ViewAccess(Envs.GetCtx(), 0, null);
                    access.SetRC_View_ID(rc.Get_ID());
                    access.SetAD_User_ID(Envs.GetCtx().GetAD_User_ID());
                    access.Save();

                    string del = "Delete from RC_ViewColumn where RC_View_ID = " + irv_view_id;
                    int res = DB.ExecuteQuery(del);

                    for (int i = 0; i <= fieldList.Count - 1; i++)
                    {
                        X_RC_ViewColumn viewcol = new X_RC_ViewColumn(Envs.GetCtx(), 0, null);
                        //viewcol.SetDescription(fieldList[i].GetKey());
                        viewcol.SetRC_View_ID(irv_view_id);
                        viewcol.SetSeqNo(i);
                        viewcol.SetAD_Field_ID(fieldList[i].GetKey());
                        b = viewcol.Save();
                    }
                }
            };

            bgw.RunWorkerCompleted += (sd, ed) =>
            {
                if (!b)
                {
                    ShowMessage.Info("NotSaved", false, "", "");
                }
                else
                {
                    ShowMessage.Info("Saved", false, "", "");

                    if (iSelectedFrame <= 0)
                    {
                        KeyNamePair newFrame = new KeyNamePair(irv_view_id, txtName.Text);
                        lstFrames.Items.Add(newFrame);
                        cmbFrame.Items.Add(newFrame);
                    }

                    ClearAll();
                }
                SetFrameBusy(false);
            };

            bgw.RunWorkerAsync();
        }

        private void btnCancelFrame_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void rdCount_Checked(object sender, RoutedEventArgs e)
        {

        }

        int isSelectedKPI = 0;

        private void btnKPIOK_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(txtSearchKey.Text))
            {
                ShowMessage.Error("EnterSearchKey", false, "");
                return;
            }
            else if (string.IsNullOrEmpty(txtKPIName.Text))
            {
                ShowMessage.Error("EnterKPIName", false, "");
                return;
            }
            else if (cmbKPICol.SelectedIndex < 0)
            {
                ShowMessage.Error("SelectKPICol", false, "");
                return;
            }
            else if (cmbKPISearch.SelectedIndex < 0)
            {
                ShowMessage.Error("SelectKPISearch", false, "");
                return;
            }
            else if (!(bool)rdSum.IsChecked)
                if(!(bool)rdCount.IsChecked)
                    if(!(bool)rdMinimum.IsChecked)
                        if(!(bool)rdMaximum.IsChecked)
                        {
                            ShowMessage.Error("SelectAggregateFunction", false, "");
                            return;
                        }

            int id = 0;
            string searchkey = txtSearchKey.Text;
            string kpiname = txtKPIName.Text;
            string kpidesc = txtKPIDesc.Text;
            int colid = (cmbKPICol.SelectedItem as KeyNamePair).GetKey();
            int searchid = (cmbKPISearch.SelectedItem as KeyNamePair).GetKey();
            bool issum = false;
            bool iscount = false;
            bool ismin = false;
            bool ismax = false;

           // string title = txt


            if ((bool)rdSum.IsChecked)
                issum = true;
            else if ((bool)rdCount.IsChecked)
                iscount = true;
            else if ((bool)rdMinimum.IsChecked)
                ismin = true;
            else if ((bool)rdMaximum.IsChecked)
                ismax = true;

            BackgroundWorker bgw = new BackgroundWorker();
            SetFrameBusy(true);
            bool b = false;
            bgw.DoWork += (sd, ed) =>
            {
                X_RC_KPI kpi = new X_RC_KPI(Envs.GetCtx(), isSelectedKPI, null);
                kpi.SetSEARCHKEY(searchkey);
                kpi.SetName(kpiname);
                kpi.SetDescription(kpidesc);
                kpi.SetAD_Column_ID(colid);
                kpi.SetAD_UserQuery_ID(searchid);
                kpi.SetIsSum(issum);
                kpi.SetIsCount(iscount);
                kpi.SetIsMinimum(ismin);
                kpi.SetIsMaximum(ismax);
                kpi.SetAD_Tab_ID(_AD_Tab_ID);
                kpi.SetAD_Table_ID(_AD_Table_ID);
                kpi.SetAD_User_ID(Envs.GetCtx().GetAD_User_ID());
                kpi.SetAD_Role_ID(Envs.GetCtx().GetAD_Role_ID());

                if (curTab.IsDetail())
                {
                    string lc = curTab.GetLinkColumnName();
                    if (!string.IsNullOrEmpty(lc))
                    {
                        string value = Envs.GetCtx().GetContext(curTab.GetWindowNo(), lc);
                        kpi.SetRecord_ID(int.Parse(value));
                    }
                }

                b = kpi.Save();

                if (b)
                {
                    //isSelectedKPI = kpi.Get_ID();
                    X_RC_KPIAccess access = new X_RC_KPIAccess(Envs.GetCtx(), 0, null);
                    access.SetRC_KPI_ID(kpi.Get_ID());
                    access.SetAD_User_ID(Envs.GetCtx().GetAD_User_ID());
                    access.Save();
                }
                id = kpi.Get_ID();
            };

            bgw.RunWorkerCompleted += (sd, ed) =>
            {
                if(b)
                    ShowMessage.Info("RecordSaved", false, "", "");
                else
                    ShowMessage.Info("SaveError", false, "", "");

                if (isSelectedKPI <= 0)
                {
                    KeyNamePair newKpi = new KeyNamePair(id, kpiname);
                    lstKPI.Items.Add(newKpi);
                    cmbKPI.Items.Add(newKpi);

                    ClearAll();
                }

                SetFrameBusy(false);
            };


            bgw.RunWorkerAsync();
        }

        private void btnKPICancel_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        private void lstKPI_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (lstKPI.SelectedIndex < 0)
                return;

            SetFrameBusy(true);
            KeyNamePair selected = (KeyNamePair)lstKPI.SelectedItem;
            isSelectedKPI = selected.GetKey();

            cmbKPICol.SelectedIndex = -1;
            cmbKPISearch.SelectedIndex = -1;
            rdSum.IsChecked = false;
            rdCount.IsChecked = false;
            rdMinimum.IsChecked = false;
            rdMaximum.IsChecked = false;

            bool isSum = false;
            bool isCount = false;
            bool isMin = false;
            bool isMax = false;
            int savedValue = -1;
            int savedCol = -1;
            ThreadPool.QueueUserWorkItem(delegate
            {
                X_RC_KPI kpi = new X_RC_KPI(Envs.GetCtx(), selected.GetKey(), null);
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => txtSearchKey.Text = kpi.GetSEARCHKEY() ?? "");
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => txtKPIName.Text = kpi.GetName() ?? "");
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => txtKPIDesc.Text = kpi.GetDescription() ?? "");
                
                isSum = kpi.IsSum();
                isCount = kpi.IsCount();
                isMin = kpi.IsMinimum();
                isMax = kpi.IsMaximum();


                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => rdSum.IsChecked = isSum);
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => rdCount.IsChecked = isCount);
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => rdMinimum.IsChecked = isMin);
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => rdMaximum.IsChecked = isMax);

                for (int i = 0; i <= ListQueries.Count - 1; i++)
                {
                    KeyNamePair current = ListQueries[i];
                    if (current.GetKey() == kpi.GetAD_UserQuery_ID())
                        savedValue = i;
                }

                for (int i = 0; i <= KPICols.Count - 1; i++)
                {
                    KeyNamePair current = KPICols[i];
                    if (current.GetKey() == kpi.GetAD_Column_ID())
                        savedCol = i;
                }

                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => cmbKPICol.SelectedIndex = savedCol);
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => cmbKPISearch.SelectedIndex = savedValue);

                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => SetFrameBusy(false));
            });
        }


        List<KeyNamePair> users = new List<KeyNamePair>();
        bool IsFrameAccess = false;

        private void rdUser_Checked(object sender, RoutedEventArgs e)
        {
            if (IsFrameAccess)
            {
                accessGrid.RowDefinitions[4].Height = new GridLength(0, GridUnitType.Pixel);
                accessGrid.RowDefinitions[3].Height = new GridLength(35, GridUnitType.Pixel);

                
                cmbUser.Items.Clear();

                cmbFrame.SelectedIndex = -1;
                vgridAcess.DataContext = null;
                vgridAcess.ItemsSource = null;
                //vdgvQuery.DataBindings.Clear();
                vgridAcess.Columns.Clear();
            }
            else
            {
                kpiAccessGrid.RowDefinitions[4].Height = new GridLength(0, GridUnitType.Pixel);
                kpiAccessGrid.RowDefinitions[3].Height = new GridLength(35, GridUnitType.Pixel);
                cmbUser1.Items.Clear();

                cmbKPI.SelectedIndex = -1;
                vgridKPIAcess.DataContext = null;
                vgridKPIAcess.ItemsSource = null;
                //vdgvQuery.DataBindings.Clear();
                vgridKPIAcess.Columns.Clear();
            }


            //Grid.SetRow(bAdd, 4);

            
            if (users.Count > 0)
            {
                for (int i = 0; i <= users.Count - 1; i++)
                {
                    if(IsFrameAccess)
                        cmbUser.Items.Add(users[i]);
                    else
                        cmbUser1.Items.Add(users[i]);
                }
            }
            else
            {
                SetFrameBusy(true);
                BackgroundWorker bgw = new BackgroundWorker();
                bgw.DoWork += (o, ev) =>
                {
                    string sql = @"select a.AD_user_ID, a.Name from AD_user a inner join AD_User_Roles b on a.ad_user_id = b.Ad_user_id
                                        where a.IsActive = 'Y' And b.ad_role_id = " + Envs.GetCtx().GetAD_Role_ID();

                    IDataReader dr = DB.ExecuteReader(sql);
                    while (dr.Read())
                    {
                        users.Add(new KeyNamePair(int.Parse(dr[0].ToString()), dr[1].ToString()));
                    }
                    dr.Close();
                };

                bgw.RunWorkerCompleted += (o, ev) =>
                {
                    for (int i = 0; i <= users.Count - 1; i++)
                    {
                        if (IsFrameAccess)
                            cmbUser.Items.Add(users[i]);
                        else
                            cmbUser1.Items.Add(users[i]);
                    }

                    SetFrameBusy(false);
                };

                bgw.RunWorkerAsync();
            }
        }


        List<KeyNamePair> roles = new List<KeyNamePair>();
        private void rdRole_Checked(object sender, RoutedEventArgs e)
        {
            if (IsFrameAccess)
            {
                accessGrid.RowDefinitions[3].Height = new GridLength(0, GridUnitType.Pixel);
                accessGrid.RowDefinitions[4].Height = new GridLength(35, GridUnitType.Pixel);
                cmbRole.Items.Clear();
                cmbFrame.SelectedIndex = -1;

                cmbFrame.SelectedIndex = -1;
                vgridAcess.DataContext = null;
                vgridAcess.ItemsSource = null;
                //vdgvQuery.DataBindings.Clear();
                vgridAcess.Columns.Clear();
            }
            else
            {
                kpiAccessGrid.RowDefinitions[3].Height = new GridLength(0, GridUnitType.Pixel);
                kpiAccessGrid.RowDefinitions[4].Height = new GridLength(35, GridUnitType.Pixel);
                cmbRole1.Items.Clear();
                cmbKPI.SelectedIndex = -1;

                cmbKPI.SelectedIndex = -1;
                vgridKPIAcess.DataContext = null;
                vgridKPIAcess.ItemsSource = null;
                //vdgvQuery.DataBindings.Clear();
                vgridKPIAcess.Columns.Clear();
            }
            
            //Grid.SetRow(bAdd, 3);

            if (roles.Count > 0)
            {
                for (int i = 0; i <= roles.Count - 1; i++)
                {
                    if (IsFrameAccess)
                        cmbRole.Items.Add(roles[i]);
                    else
                        cmbRole1.Items.Add(roles[i]);
                }
            }
            else
            {
                SetFrameBusy(true);
                BackgroundWorker bgw = new BackgroundWorker();
                bgw.DoWork += (o, ev) =>
                {
                    string sql = "Select AD_Role_ID, Name from AD_Role Where IsActive = 'Y' And AD_Client_ID = " + Envs.GetCtx().GetAD_Client_ID();
                    IDataReader dr = DB.ExecuteReader(sql);
                    while (dr.Read())
                    {
                        roles.Add(new KeyNamePair(int.Parse(dr[0].ToString()), dr[1].ToString()));
                    }
                    dr.Close();
                };

                bgw.RunWorkerCompleted += (o, ev) =>
                {
                    for (int i = 0; i <= roles.Count - 1; i++)
                    {
                        if (IsFrameAccess)
                            cmbRole.Items.Add(roles[i]);
                        else
                            cmbRole1.Items.Add(roles[i]);
                    }

                    SetFrameBusy(false);
                };

                bgw.RunWorkerAsync();
            }
        }

        private void bAdd1_Click(object sender, RoutedEventArgs e)
        {
            if (cmbFrame.SelectedIndex < 0)
            {
                ShowMessage.Error("SelectFrame", false);
                return;
            }
            else if ((bool)rdRole.IsChecked && cmbRole.SelectedIndex < 0)
            {
                ShowMessage.Error("SelectRole", false);
                return;
            }
            else if ((bool)rdUser.IsChecked && cmbUser.SelectedIndex < 0)
            {
                ShowMessage.Error("SelectUser", false);
                return;
            }


            SetFrameBusy(true);

            bool isRole = (bool)rdRole.IsChecked;
            bool isUser = (bool)rdUser.IsChecked;

            bool b = false;
            int rcviewid = (cmbFrame.SelectedItem as KeyNamePair).GetKey();
            int roleid = 0;
            if((bool)rdRole.IsChecked)
                roleid = (cmbRole.SelectedItem as KeyNamePair).GetKey();

            int userid = 0;
            if((bool)rdUser.IsChecked)
                userid = (cmbUser.SelectedItem as KeyNamePair).GetKey();

            BackgroundWorker bgw = new BackgroundWorker();
            bgw.DoWork += (o, ev) =>
            {
                X_RC_ViewAccess access = new X_RC_ViewAccess(Envs.GetCtx(), 0, null);
                access.SetRC_View_ID(rcviewid);
                if (isRole)
                    access.SetAD_Role_ID(roleid);
                else
                    access.SetAD_User_ID(userid);

                b = access.Save();
            };

            bgw.RunWorkerCompleted += (o, ev) =>
                {
                    if (b)
                    {
                        ShowMessage.Info("Saved", false, "", "");

                        if (dsAccess.Tables.Count == 0)
                        {
                            DataTable dt = new DataTable();

                            DataColumn dc;
                            dc = new DataColumn("RC_VIEWACCESS_ID");
                            dt.Columns.Add(dc);
                            //dsAdvanceData.Tables[0].Columns.Add(dc);
                            dc = new DataColumn("FRAME");
                            dt.Columns.Add(dc);
                            //dsAdvanceData.Tables[0].Columns.Add(dc);
                            dc = new DataColumn("ROLE");
                            dt.Columns.Add(dc);
                            //dsAdvanceData.Tables[0].Columns.Add(dc);
                            dc = new DataColumn("USERS");
                            dt.Columns.Add(dc);
                        }

                        // new row
                        DataRow dr = dsAccess.Tables[0].NewRow();
                        // set values in new row
                        dr[0] = 0;
                        dr[1] = (cmbFrame.SelectedItem as KeyNamePair).GetName();
                        dr[2] = isRole == true ? (cmbRole.SelectedItem as KeyNamePair).GetName() : "";
                        dr[3] = isUser == true ? (cmbUser.SelectedItem as KeyNamePair).GetName() : "";

                        dsAccess.Tables[0].Rows.Add(dr);
                        BindAccecssGrid(dsAccess);//for the time beeing commented today 3Dec.2010

                    }
                    else
                        ShowMessage.Info("NotSaved", false, "", "");

                    SetFrameBusy(false);
                };

            bgw.RunWorkerAsync();
        }


        public void GetAccessRecords()
        {
            KeyNamePair select = null;
            
            if(IsFrameAccess)
                select = (KeyNamePair)cmbFrame.SelectedItem;
            else
                select = (KeyNamePair)cmbKPI.SelectedItem;

            if (select == null)
                return;

            int id = select.GetKey();
            BackgroundWorker bgw = new BackgroundWorker();
            bool isRole = false;

            if (IsFrameAccess)
                isRole = (bool)rdRole.IsChecked;
            else
                isRole = (bool)rdRole1.IsChecked;



            bgw.DoWork += (o, ev) =>
            {
                string tableName = IsFrameAccess == true ? "RC_View" : "RC_KPI";
                string accesstable = IsFrameAccess == true ? "RC_ViewAccess" : "RC_KPIAccess";
                string colName = isRole == true ? "c.AD_Role_ID" : "d.AD_User_ID";
                string sql = @"select a." + accesstable + @"_ID AS RC_ViewAccess_ID, b.Name as FRAME, c.Name as ROLE, d.Name as USERS from " + accesstable + @" a 
                                inner join " + tableName + @" b on a." + tableName + @"_ID = b." + tableName + @"_ID 
                                left join ad_role c on a.ad_role_id = c.ad_role_id
                                left join ad_user d on a.ad_user_id = d.ad_user_id 
                                WHERE " + colName + @" > 0 AND a." + tableName + @"_ID = " + id + @" Order by c.Name";

                dsAccess = DB.ExecuteDataset(sql, null);
            };

            bgw.RunWorkerCompleted += (o, ev) =>
                {
                    BindAccecssGrid(dsAccess);
                };

            bgw.RunWorkerAsync();
        }

        /// <summary>
        /// Bind grid to given dataset
        /// </summary>
        /// <param name="ds">dataset</param>
        private void BindAccecssGrid(DataSet ds)
        {
            if (IsFrameAccess)
            {
                // clear and unbind the grid
                vgridAcess.DataContext = null;
                vgridAcess.ItemsSource = null;
                //vdgvQuery.DataBindings.Clear();
                vgridAcess.Columns.Clear();
                vgridAcess.AutoGenerateColumns = false;
            }
            else
            {
                // clear and unbind the grid
                vgridKPIAcess.DataContext = null;
                vgridKPIAcess.ItemsSource = null;
                //vdgvQuery.DataBindings.Clear();
                vgridKPIAcess.Columns.Clear();
                vgridKPIAcess.AutoGenerateColumns = false;
            }

            //1. "Column" Column KEYNAME
            DataGridTextColumn columnObj = new DataGridTextColumn();
            columnObj.Header = Msg.Translate(_ctx, "RC_VIEWACCESS_ID");
            columnObj.Binding = new System.Windows.Data.Binding("RC_VIEWACCESS_ID");
            columnObj.IsReadOnly = true;
            if(IsFrameAccess)
                vgridAcess.Columns.Add(columnObj);
            else
                vgridKPIAcess.Columns.Add(columnObj);

            //2. "Column" Column KEYVALUE
            DataGridTextColumn keyvalueObj = new DataGridTextColumn();
            keyvalueObj.Header = Msg.Translate(_ctx, "FRAME");
            keyvalueObj.Binding = new System.Windows.Data.Binding("FRAME");
            keyvalueObj.IsReadOnly = true;

            if(IsFrameAccess)
                vgridAcess.Columns.Add(keyvalueObj);
            else
                vgridKPIAcess.Columns.Add(keyvalueObj);


            //3. "Operator" Column OPERATORNAME
            DataGridTextColumn opNameObj = new DataGridTextColumn();
            opNameObj.Header = Msg.Translate(_ctx, "ROLE");
            opNameObj.Binding = new System.Windows.Data.Binding("ROLE");
            opNameObj.IsReadOnly = true;

            if(IsFrameAccess)
                vgridAcess.Columns.Add(opNameObj);
            else
                vgridKPIAcess.Columns.Add(opNameObj);



            //4. "Query Value" Column VALUE1NAME
            DataGridTextColumn valueObj = new DataGridTextColumn();
            valueObj.Header = Msg.Translate(_ctx, "USERS");
            valueObj.Binding = new System.Windows.Data.Binding("USERS");
            valueObj.IsReadOnly = true;

            if(IsFrameAccess)
                vgridAcess.Columns.Add(valueObj);
            else
                vgridKPIAcess.Columns.Add(valueObj);


            ///DataGridBoundColumn bc = new DataGridBoundColumn();
            Grids.DataGridImageColumn img = new DataGridImageColumn();
            img.Image = Envs.LoadImageSource("delete.png");

            img.Header = "Action";

            img.Click += new RoutedEventHandler(imgAccess_Click);

            if(IsFrameAccess)
                vgridAcess.Columns.Add(img);
            else
                vgridKPIAcess.Columns.Add(img);

            // if user has given any dataset
            if (ds != null)
            {
                if(IsFrameAccess)
                    vgridAcess.ItemsSource = ds.Tables[0].GetBindableData(new Connector());
                else
                    vgridKPIAcess.ItemsSource = ds.Tables[0].GetBindableData(new Connector());
            }

            if (IsFrameAccess)
            {
                vgridAcess.Columns[0].Visibility = System.Windows.Visibility.Collapsed;
                if ((bool)rdRole.IsChecked)
                    vgridAcess.Columns[3].Visibility = System.Windows.Visibility.Collapsed;
                else
                    vgridAcess.Columns[2].Visibility = System.Windows.Visibility.Collapsed;
            }
            else
            {
                vgridKPIAcess.Columns[0].Visibility = System.Windows.Visibility.Collapsed;
                if ((bool)rdRole1.IsChecked)
                    vgridKPIAcess.Columns[3].Visibility = System.Windows.Visibility.Collapsed;
                else
                    vgridKPIAcess.Columns[2].Visibility = System.Windows.Visibility.Collapsed;
            }
        }

        void imgAccess_Click(object sender, RoutedEventArgs e)
        {
            SetFrameBusy(true);
            int index = IsFrameAccess == true ?  vgridAcess.SelectedIndex : vgridKPIAcess.SelectedIndex;
            int data = 0;
            if (index > -1)
            {
                data = int.Parse(dsAccess.Tables[0].Rows[index][0].ToString());
                bool b = false;
                BackgroundWorker bgw = new BackgroundWorker();
                bgw.DoWork += (o, ev) =>
                    {
                        if (IsFrameAccess)
                        {
                            X_RC_ViewAccess access = new X_RC_ViewAccess(Envs.GetCtx(), data, null);
                            b = access.Delete(true);
                        }
                        else
                        {
                            X_RC_KPIAccess access = new X_RC_KPIAccess(Envs.GetCtx(), data, null);
                            b = access.Delete(true);
                        }
                    };

                bgw.RunWorkerCompleted += (o, ev) =>
                    {
                        if (b)
                        {
                            ShowMessage.Info("Deleted", false, "", "");

                            dsAccess.Tables[0].Rows.RemoveAt(index);
                            BindAccecssGrid(dsAccess);
                        }

                        SetFrameBusy(false);
                    };

                bgw.RunWorkerAsync();
            }
        }

        private void cmbFrame_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            GetAccessRecords();
        }

        private void rdPersonal1_Checked(object sender, RoutedEventArgs e)
        {

        }

        private void rdPersonal_Checked(object sender, RoutedEventArgs e)
        {

        }

        private void cmbKPI_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            GetAccessRecords();
        }

        private void bAddKPI_Click(object sender, RoutedEventArgs e)
        {
            if (cmbKPI.SelectedIndex < 0)
            {
                ShowMessage.Error("SelectFrame", false);
                return;
            }
            else if ((bool)rdRole1.IsChecked && cmbRole1.SelectedIndex < 0)
            {
                ShowMessage.Error("SelectRole", false);
                return;
            }
            else if ((bool)rdUser1.IsChecked && cmbUser1.SelectedIndex < 0)
            {
                ShowMessage.Error("SelectUser", false);
                return;
            }


            SetFrameBusy(true);

            bool isRole = (bool)rdRole1.IsChecked;
            bool isUser = (bool)rdUser1.IsChecked;

            bool b = false;
            int rcviewid = (cmbKPI.SelectedItem as KeyNamePair).GetKey();
            int roleid = 0;
            if ((bool)rdRole1.IsChecked)
                roleid = (cmbRole1.SelectedItem as KeyNamePair).GetKey();

            int userid = 0;
            if ((bool)rdUser1.IsChecked)
                userid = (cmbUser1.SelectedItem as KeyNamePair).GetKey();

            BackgroundWorker bgw = new BackgroundWorker();
            bgw.DoWork += (o, ev) =>
            {
                X_RC_KPIAccess access = new X_RC_KPIAccess(Envs.GetCtx(), 0, null);
                access.SetRC_KPI_ID(rcviewid);
                if (isRole)
                    access.SetAD_Role_ID(roleid);
                else
                    access.SetAD_User_ID(userid);

                b = access.Save();
            };

            bgw.RunWorkerCompleted += (o, ev) =>
            {
                if (b)
                {
                    ShowMessage.Info("Saved", false, "", "");

                    if (dsAccess.Tables.Count == 0)
                    {
                        DataTable dt = new DataTable();

                        DataColumn dc;
                        dc = new DataColumn("RC_VIEWACCESS_ID");
                        dt.Columns.Add(dc);
                        //dsAdvanceData.Tables[0].Columns.Add(dc);
                        dc = new DataColumn("FRAME");
                        dt.Columns.Add(dc);
                        //dsAdvanceData.Tables[0].Columns.Add(dc);
                        dc = new DataColumn("ROLE");
                        dt.Columns.Add(dc);
                        //dsAdvanceData.Tables[0].Columns.Add(dc);
                        dc = new DataColumn("USERS");
                        dt.Columns.Add(dc);
                    }

                    // new row
                    DataRow dr = dsAccess.Tables[0].NewRow();
                    // set values in new row
                    dr[0] = 0;
                    dr[1] = (cmbKPI.SelectedItem as KeyNamePair).GetName();
                    dr[2] = isRole == true ? (cmbRole1.SelectedItem as KeyNamePair).GetName() : "";
                    dr[3] = isUser == true ? (cmbUser1.SelectedItem as KeyNamePair).GetName() : "";

                    dsAccess.Tables[0].Rows.Add(dr);
                    BindAccecssGrid(dsAccess);//for the time beeing commented today 3Dec.2010

                }
                else
                    ShowMessage.Info("NotSaved", false, "", "");

                SetFrameBusy(false);
            };

            bgw.RunWorkerAsync();
        }

        private void ChildWindow_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.PlatformKeyCode == 13)
            {
               // string curTab = (vtabLookup.SelectedItem as TabItem).Header;
                if (curTab != null)
                {
                    if ((vtabLookup.SelectedItem as TabItem).Header.ToString().Equals("LookupRecords"))
                    {
                        ibtnOKS_Click(sender, new RoutedEventArgs());
                    }
                    else if ((vtabLookup.SelectedItem as TabItem).Header.Equals("Advance"))
                    {
                        ibtnOKA_Click(sender, new RoutedEventArgs());
                    }
                    else if ((vtabLookup.SelectedItem as TabItem).Header.Equals("View"))
                    {
                        btnSaveFrame_Click(sender, new RoutedEventArgs());
                    }
                    else if ((vtabLookup.SelectedItem as TabItem).Header.Equals("KPI"))
                    {
                        btnKPIOK_Click(sender, new RoutedEventArgs());
                    }
                }
            }

        }

        
    }
}